Friday, October 16, 2009

Unzipping .gz files in Java

Unzipping files in easy, just double click and the OS unzips it using the default application.

What in case there are hundred of files in a folder you want to unzip. (We won't go into the details of why we want to unzip the files, when we can directly read the zipped version... That's another story).

Task: How to unzip a ".gz" file using Java.

Tools: Classes GZIPInputStream and OutputStream helps us to do the task.

GZIPInputStream gzipInputStream = new GZIPInputStream(newFileInputStream(inFilename));

OutputStream out = new FileOutputStream(outFilename);

byte[] buf = new byte[102400]; //size can be changed according to programmer's need.
int len;
while ((len = > 0) {
out.write(buf, 0, len);

The main points to note here are:-
a) GZIPInputStream class which creates a inputStream for the file to be read.
b) function, reads the uncompressed data into the buffer. The return type of this function is int, which specifies the number of bytes read.
c) The data read can be written into a FileOutputStream in uncompressed form.

So easy to unzip files.


Kapil Dalwani


  1. Hi Kapil,
    I tried your code but it was not working.
    It caused an Exception as follows:
    Exception in thread "main" Corrupt GZIP trailer

  2. I'm getting the same error when trying to uncompress a gzipped bytearrayinputstream.

  3. It workerd for me. seems like Some thing wrong with your file.
    Convert your file to gz using gzip command...and try

  4. i am also getting same issue..when i am retrieving '*.gz' file from ftp...