blog rss feed

Reading ZIP, GZIP and JAR files with Java inbuilt classes

Keywords:

Last editor: Dave Cherry, last modified: Oct 25, 2009

Dealing with files in the gzip format.

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:

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

public class ZipReader
{
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();
}
}
}

So what did the above do?

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).

Please leave a comment



Search

Blog calendar

blog: previous month September 2010 blog: next month
su mo tu we th fr sa
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30