Another common compression file format on Linux is the GZIP format. Java again has out of the box support for this file format. Gzip files differ from zip files in that they only contain one file, the compressed form of the original file with a .gz extension.
Java’s GZipInputStream
takes such a file type and decompresses it. We can treat GZipInputStream
directly like a
FileInputStream
. Here is an example that expands such a file to disk
package com.thecoderscorner.example.compression;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
public class GzipReader
{
public static void main(String[] args) throws IOException
{
if(args.length != 1)
{
System.out.println("Please enter filename");
return;
}
// open the input (compressed) file.
FileInputStream stream = new FileInputStream(args[0]);
FileOutputStream output = null;
try
{
// open the gziped file to decompress.
GZIPInputStream gzipstream = new GZIPInputStream(stream);
byte[] buffer = new byte[2048];
// create the output file without the .gz extension.
String outname = args[0].substring(0, args[0].length()-3);
output = new FileOutputStream(outname);
// and copy it to a new file
int len;
while((len = gzipstream.read(buffer ))>0)
{
output.write(buffer, 0, len);
}
}
finally
{
// both streams must always be closed.
if(output != null) output.close();
stream.close();
}
}
}
The above code created an uncompressed version of the .gz file that was passed in to it, (removing the gz extension in the output file).