Search code examples
javaalgorithmarchive

How to decompress .tgz files in java


I want to know, how to decompress .tgz file to .tar using apache commons. As i am able to extract the .tar file but for .tgz file first i need to bring it to .tar which I seems to be an issue for me. .tgz file is something which i need to unzip it first so that .tar will be available. However, zip extraction is not working on .tgz file for me.

My main concern is , how to decompress .tgz file to .tar.

any suggestion. thanks.


Solution

  • You don't need Apache Commons for .tgz to tar. That's because .tgz is .tar with GZIP compression applied. Create an InputStream for the file, wrap it in a GZIPInputStream, and read from that. You can use that directly in creating a TarArchiveInputStream if you want:

    try (InputStream source = Files.newInputStream(file);
            GZIPInputStream gzip = new GZIPInputStream(source);
            TarArchiveInputStream tar = new TarArchiveInputStream(gzip)) {
    
        TarArchiveEntry entry;
        while ((entry = tar.getNextTarEntry()) != null) {
            // do somthing with entry
        }
    }