How do I compress and uncompress a gzip file?
Author: Deron Eriksson
Description: This Java tutorial describes how to compress and uncompress a gzip file.
Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 2.0 (Eclipse 3.3.0)


In another tutorial, we saw how we could deflate and inflate files using DeflaterOutputStream and InflaterInputStream. If we replace DeflaterOutputStream with GZIPOutputStream and InflaterInputStream with GZIPInputStream, we can then use the same code to compress data to a file and uncompress data from a compressed file.

The GZIPCompressUncompressTest class reads a regular text file, "original.txt". It copies this data to a file called "compressed.gz", but as it writes the data, the data passes through a GZIPOutputStream, which compresses the data into gzip format. It then reads "compressed.gz" and it uncompresses the gzip stream of data by passing it through a GZIPInputStream. It writes the uncompressed data to a new text file, "uncompressed.txt". So, this class basically copies "original.txt" to "uncompressed.txt", with the "compressed.gz" as a compressed intermediary file.

GZIPCompressUncompressTest.java

package test;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class GZIPCompressUncompressTest {

	public static void main(String[] args) throws Exception {

		FileInputStream fis = new FileInputStream("original.txt");
		FileOutputStream fos = new FileOutputStream("compressed.gz");
		GZIPOutputStream gos = new GZIPOutputStream(fos);

		doCopy(fis, gos); // copy and compress

		FileInputStream fis2 = new FileInputStream("compressed.gz");
		GZIPInputStream gis = new GZIPInputStream(fis2);
		FileOutputStream fos2 = new FileOutputStream("uncompressed.txt");

		doCopy(gis, fos2); // copy and uncompress

	}

	public static void doCopy(InputStream is, OutputStream os) throws Exception {
		int oneByte;
		while ((oneByte = is.read()) != -1) {
			os.write(oneByte);
		}
		os.close();
		is.close();
	}

}