25

I can uncompress zip, gzip, and rar files, but I also need to uncompress bzip2 files as well as unarchive them (.tar). I haven't come across a good library to use.

I am using Java along with Maven so ideally, I'd like to include it as a dependency in the POM.

What libraries do you recommend?

Kalle Richter
  • 8,008
  • 26
  • 77
  • 177

2 Answers2

42

The best option I can see is Apache Commons Compress with this Maven dependency.

<dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-compress</artifactId>
  <version>1.0</version>
</dependency>

From the examples:

FileInputStream in = new FileInputStream("archive.tar.bz2");
FileOutputStream out = new FileOutputStream("archive.tar");
BZip2CompressorInputStream bzIn = new BZip2CompressorInputStream(in);
final byte[] buffer = new byte[buffersize];
int n = 0;
while (-1 != (n = bzIn.read(buffer))) {
  out.write(buffer, 0, n);
}
out.close();
bzIn.close();
cletus
  • 616,129
  • 168
  • 910
  • 942
  • 3
    To copy the streams, you can also use Apache Commons IO's [IOUtils.copyLarge](http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/IOUtils.html#copyLarge%28java.io.InputStream,%20java.io.OutputStream%29). – thSoft Aug 01 '15 at 10:26
4

Please don't forget to use buffered streams to gain up to 3x speedup!

public void decompressBz2(String inputFile, String outputFile) throws IOException {
    var input = new BZip2CompressorInputStream(new BufferedInputStream(new FileInputStream(inputFile)));
    var output = new FileOutputStream(outputFile);
    try (input; output) {
        IOUtils.copy(input, output);
    }
}

decompressBz2("example.bz2", "example.txt");

With build.gradle.kts:

dependencies {
    ...
    implementation("org.apache.commons:commons-compress:1.20")
}
diralik
  • 6,391
  • 3
  • 28
  • 52