Gzip and gunzip a file

From CodeCodex

Revision as of 23:15, 17 February 2012 by Nostromo (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

The following code samples show how to gzip and gunzip files.



Use these imports:

import java.util.zip.*;
import java.io.*;

And here is the method to unzip a file.

public static String Unzip(String inFilePath) throws Exception
    GZIPInputStream gzipInputStream = new GZIPInputStream(new FileInputStream(inFilePath));
    String outFilePath = inFilePath.replace(".gz", "");
    OutputStream out = new FileOutputStream(outFilePath);
    byte[] buf = new byte[1024];
    int len;
    while ((len = gzipInputStream.read(buf)) > 0)
        out.write(buf, 0, len);
    new File(inFilePath).delete();
    return outFilePath;