GZIPping with Java - And the Other Way Around: Uncompressing Your GZIP Files (Programmatically)
(Page 4 of 5 )
Decompressing a gzip file with the java.util.zip API is pretty straightforward too. The class below decompresses the file we created in the previous section. The class begins by creating a new GZIPInputStream stream object. We pass the GZIPInputStream constructor the filename of the gzip file we want to decompress (i.e., c:\articles\examplegzip.gz). Next, we use the same byte buffer technique to read from the GZIPInputStream object and write to a FileOutputStream object. To clean things up, we close our GZIPInputStream and our OutputStream. Our sample program will create a file named statebirdsclone.txt, which is exactly the same as its original, statebirds.txt that we compressed in the previous section.
// Open the gzip file
String inFilename = "c:\articles\examplegzip.gz";
GZIPInputStream gzipInputStream =
new GZIPInputStream(new FileInputStream(inFilename));
// Open the output file
String outFilename = "c:\articles\statebirdsclone.txt";
OutputStream out = new FileOutputStream(outFilename);
// Transfer bytes from the compressed file to the output file
byte[] buf = new byte[1024];
int len;
while ((len = gzipInputStream.read(buf)) > 0) {
out.write(buf, 0, len);
}
// Close the file and stream
gzipInputStream.close();
out.close();
After reading the entire file using the GZIPInputStream, the read method will compare the checksum of the decompressed data with the checksum that is stored in the trailer of the GZIP file. If the values do not match, the read method will throw an exception.
Next: Leveraging GZIP in the Web World >>
More Java Articles
More By Kulvir Singh Bhogal