Tuesday, February 5, 2013

Java service to create a Tar file using Apache Commons Compress library.

There is often a need to create a Tar file by archiving logs files or other files. You could create a tar file using Native Java libraries as well as third party libraries. The advantage of using third party libraries is that it  provides out of the box methods to write the files. The disadvantage would be to go through the license agreements on the jars and make sure you are not violating any of their agreements.


IDataCursor pipelineCursor = pipeline.getCursor();
String directoryName = IDataUtil.getString( pipelineCursor, "directoryName" );
pipelineCursor.destroy();
  
File dirName=new File(directoryName);
File[] fileNames=dirName.listFiles();  
OutputStream tarfileOutstream;  
try {
      tarfileOutstream = new FileOutputStream(new File("E:/aarremreddy/Tasks/Compress/test.tar"));
      ArchiveOutputStream aos = new ArchiveStreamFactory().createArchiveOutputStream(ArchiveStreamFactory.TAR, tarfileOutstream);
     
      for(int i=0;i<fileNames.length;i++){
 File tarInputfile= fileNames[i];
 TarArchiveEntry archiveEntry = new TarArchiveEntry(tarInputfile);
 archiveEntry.setSize(tarInputfile.length());
 aos.putArchiveEntry(archiveEntry);
 IOUtils.copy(new FileInputStream(tarInputfile),aos);
 aos.closeArchiveEntry();
      }

    aos.finish(); 
    tarfileOutstream.close();
    IDataUtil.put(pipelineCursor, "result", "Success");
} 
catch (FileNotFoundException e) {
 IDataUtil.put(pipelineCursor, "result", e.toString());
} catch (ArchiveException e) {
 IDataUtil.put(pipelineCursor, "result", e.toString());
} catch (IOException e) {
 IDataUtil.put(pipelineCursor, "result", e.toString());
}
Imports:
import org.apache.commons.compress.archivers.ArchiveException;
import org.apache.commons.compress.archivers.ArchiveOutputStream;
import org.apache.commons.compress.archivers.ArchiveStreamFactory;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.utils.IOUtils;
Jars:
commons-compress-1.4.1.jar;
commons-io-2.4.jar;

No comments:

Post a Comment