Extract files from *.gz extension

I have successfully extracted *.gz from *.tgz and now I have no idea how to actually extract final files from *.tgz.

There are some options using custom packages but that's not an option for me, I need to use standard Java packages only.

What I tried is using same function that I use for *.tgz for *.gz but it doesn't work.

java.util.zip.ZipException: Not in GZIP format 1.gz

Here is function that is extracting *.tgz files.

public String ExtractFile(String path) {
    try {
        File newFile = new File(this.getFullPathWithoutExtension(path) + ".gz");

        GZIPInputStream gStream;
        FileOutputStream outStream;
        try (FileInputStream fileStream = new FileInputStream(path)) {
            gStream = new GZIPInputStream(fileStream);
            outStream = new FileOutputStream(newFile);
            byte[] buf = new byte[1024];
            int len;
            while ((len = gStream.read(buf)) > 0) {
                outStream.write(buf, 0, len);
            }
        }
        gStream.close();
        outStream.close();

        newFile.createNewFile();

        return newFile.getPath();

    } catch (Exception e) {
        System.out.print(e);
    }

    return null;
}

TL;DR; *.tgz files extracted to *.gz files, however *.gz files cannot be extracted.

Jon Skeet
people
quotationmark

A .tgz file wouldn't normally be extracted to a .gz file - it would be extracted to a .tar file. (A .gz file is gzipped; a .tar file is an uncompressed archive containing multiple files; a .tgz is a .tar file that's then been gzipped - you've already "undone" the gzipping.)

I don't think there's anything within Java's standard libraries to handle tar files - so you'll either have to revisit your "I can't use anything not in the standard library" decision or reimplement it yourself. The file format is easily available if you decide to do that.

people

See more on this question at Stackoverflow