Java I/O How to - Unzip a file with GZIPInputStream








Question

We would like to know how to unzip a file with GZIPInputStream.

Answer

 /* w  ww  .j a  v a2  s  .  c  om*/


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

public class Main {
  public static void main(String[] args) throws Exception {
    int sChunk = 8192;

    String zipname = "a.txt.gz";
    String source = "a.txt";
    FileInputStream in = new FileInputStream(zipname);
    GZIPInputStream zipin = new GZIPInputStream(in);
    byte[] buffer = new byte[sChunk];
    FileOutputStream out = new FileOutputStream(source);
    int length;
    while ((length = zipin.read(buffer, 0, sChunk)) != -1)
      out.write(buffer, 0, length);
    out.close();
    zipin.close();
  }
}