01-07-2012

Another common compression file format on Linux is the GZIP format. Java again has out of the box support for this file format. Gzip files differ from zip files in that they only contain one file, the compressed form of the original file with a .gz extension.

Java's GZipInputStream takes such a file type and decompresses it. We can treat GZipInputStream directly like a FileInputStream. Here is an example that expands such a file to disk

package com.thecoderscorner.example.compression;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;

public class GzipReader
{
    public static void main(String[] args) throws IOException
    {
        if(args.length != 1)
        {
            System.out.println("Please enter filename");
            return;
        }

        // open the input (compressed) file.
        FileInputStream stream = new FileInputStream(args[0]);
        FileOutputStream output = null;
        try
        {
            // open the gziped file to decompress.
            GZIPInputStream gzipstream = new GZIPInputStream(stream);
            byte[] buffer = new byte[2048];

            // create the output file without the .gz extension.
            String outname = args[0].substring(0, args[0].length()-3);
            output = new FileOutputStream(outname);

            // and copy it to a new file
            int len;
            while((len = gzipstream.read(buffer ))>0)
            {
                output.write(buffer, 0, len);
            }
        }
        finally
        {
            // both streams must always be closed.
            if(output != null) output.close();
            stream.close();
        }
    }
}

So what did the above do?

The above code created an uncompressed version of the .gz file that was passed in to it, (removing the gz extension in the output file).

These may be of interest

We use cookies to analyse traffic and to personalise content. We also embed Twitter and Youtube on some pages, these companies have their own privacy policies.

See the privacy policy and terms of use of this site should you need more information or wish to adjust your settings.