One of the most common compression algorithms out there is gzip. Therefore you are likely to need to compress files using gzip at some time or another. Below is an example of doing this in Java.

First create a FileInputStream from the file to be compressed. The data is read, and a compressed version of the contents are written to disk using GZIPOutputStream and FileOutputStream. The end result of this program is the creation of a gzipped copy of “sample_data_1.txt” on the local filesystem.

package com.bigdatums.compression;


public class GZip {

    public static final int bufferSize = 1024;

    public void GZipFile(String inputPath, String outputPath) throws Exception {

        FileInputStream fis = new FileInputStream(inputPath);
        FileOutputStream fos = new FileOutputStream(outputPath);
        GZIPOutputStream gos = new GZIPOutputStream(fos);
        byte[] buffer = new byte[bufferSize];

            int len;
            while((len = != -1) {
                 gos.write(buffer, 0, len);
        } finally {
            try{if(fis != null) fis.close();} catch(Exception e){}
            try{if(gos != null) gos.close();} catch(Exception e){}

    public static void main(String[] args) throws Exception {
        GZip gz = new GZip();
        gz.GZipFile("sample_data_1.txt", "sample_data_1.txt.gz");


Leave a Reply

How to GZip a File in Java