By dave | July 1, 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).

Other pages within this category

comments powered by Disqus

This site uses cookies to analyse traffic, serve ads by Google AdSense (non-personalized in EEA/UK), and to record consent. We also embed Twitter, Youtube and Disqus content on some pages, these companies have their own privacy policies.

Our privacy policy applies to all pages on our site

Should you need further guidance on how to proceed: External link for information about cookie management.