Quick way to untar and bunzip files in java

Have you ever felt a need to deal with bzip2 compressed tarballs in Java? Recently I compressed a lot of test resources in our source tree using bzip2 compression. The resources were static and were meant to change very rarely. bzip2 was the best choice in terms of amount of compression. What it also meant was my SVN download of the source tree would take much lower time. I planned to extract the resources and make them available at runtime while running tests.

If you already know, there is no way to handle bzip compression in Java core API. But at the back of my mind I knew that you can create bzipped tarballs using Ant. So I looked at the Ant tasks and figured that there was untar task which can be instructed to also process it through bzip2 uncompression.

Here is the code snippet that can untar and bunzip the file using Java code.
Untar untar = new Untar();
untar.setSrc(new File("./src/test/resources/files.tar.bz2"));
untar.setDest(new File("./target"));
UntarCompressionMethod compression = new UntarCompressionMethod();
compression.setValue("bzip2");
untar.setCompression(compression);
untar.setOverwrite(true);
untar.execute();

Also make sure that you put ant jar on the classpath.

Maven users can simply add following dependency,

<dependency>
   <groupId>org.apache.ant</groupId>
   <artifactId>ant</artifactId>
   <version>1.7.0</version>
   <scope>test</scope>
</dependency>

0 comments :