tags:

views:

4452

answers:

2

How do I extract a tar (or tar.gz, or tar.bz2) file in Java?

+3  A: 

What about using this API for tar files, this other one included inside Ant for BZIP2 and the standard one for GZIP?

Fernando Miguélez
+4  A: 

I haven't used a tar API directly, but tar and bzip2 are implemented in Ant; you could borrow their implementation, or possibly use Ant to do what you need.

Gzip is part of Java SE (and I'm guessing the Ant implementation follows the same model).

GZIPInputStream is just an InputStream decorator. You can wrap, for example, a FileInputStream in a GZIPInputStream and use it in the same way you'd use any InputStream:

InputStream is = new GZIPInputStream(new FileInputStream(file));

(Note that the GZIPInputStream has its own, internal buffer, so wrapping the FileInputStream in a BufferedInputStream would probably decrease performance.)

erickson
i was about to tell him about GZIPInputStream. But it won't help him, since he still needs to read the contained .tar file :)
Johannes Schaub - litb
Truth is I already know about GZIPInputStream, thanks to another question I asked here. But I don't know anything about tar APIs, and I was hoping there might be something that handles gzip in an integrated manner, so I didn't want to limit answers by saying what all I already knew.
skiphoppy
Apache classes bundled in 'ant' work fine. I use this every day: org.apache.tools.tar.TarEntry and org.apache.tools.tar.TarInputStream; the code is very similar to what you would use to unzip zip files. If you want to do Bzip2, use jaxlib.
tucuxi