Friday, June 08, 2012

Extract Tar File In ColdFusion

In ColdFusion it doesn't have any built in function to extract a ".tar" or any ".gz" Compression. For ".gz" compression I have already posted a tip. Now, I am just going to give show you a ColdFusion function using which can be used to extract tar files. This function uses Apache java library to extract the ".tar" file.
Lets start:

<cfscript>
    /*
    @inTarFilePath = input tar file absolute path
    @outExtractPath = The out put directory to which the files will be extract.
    
    Example:
    tarExtract("D:\Temp\pics-leaserental-20120530.tar", "D:\Temp\TarResult\");
    */
    function tarExtract(inTarFilePath, outExtractPath)
    {
        var fileInStream = createObject("java", "java.io.FileInputStream");
        var fileOutStream = createObject("java", "java.io.FileOutputStream");
        var tarInStream = createObject("java", "org.apache.tools.tar.TarInputStream");
        var tarEntry = createObject("java", "org.apache.tools.tar.TarEntry");
        var destFileName = "";

        try{

            //Read tar stream
            fileInStream.init(arguments.inTarFilePath);
            tarInStream.init(fileInStream);
            tarEntry = tarInStream.getNextEntry();

            //Loop each tar entry and write in the specific directory
            while(! isNull(tarEntry)){
                destFileName = arguments.outExtractPath & '/' & tarEntry.getName();

                //If the tar entry is not a directory(means it is a file) then write write that in a file
                if(! tarEntry.isDirectory()){
                    fileOutStream.init(destFileName);
                    tarInStream.copyEntryContents(fileOutStream);
                    fileOutStream.close();
                }
                tarEntry = tarInStream.getNextEntry();

            }

            //Close all opened file streams
            fileInStream.close();
            tarInStream.close();

            return true;
        } catch(Any e){
            return false;
        }
    }
</cfscript>


Hope it will help you in sometime...

No comments:

Post a Comment

Followers