Java Reference
In-Depth Information
Working with GZIP File Format
The
GZIPInputStream
and
GZIPOutputStream
classes are used to work with the GZIP file format. They are concrete
decorator classes in the
InputStream
and
OutputStream
class families. Their usage is similar to any other concrete
decorator classes for I/O. You need to wrap your
OutputStream
object inside an object of
GZIPOutputStream
to apply GZIP
compression to your data. You need to wrap your
InputStream
object inside a
GZIPInputStream
object to apply GZIP
decompression. The following snippet of code illustrates how to use these classes to compress and decompress data:
// Create a GZIPOutputStream object to compress data in GZIP format
// and write it to gziptest.gz file.
GZIPOutputStream gos = new GZIPOutputStream(new FileOutputStream("gziptest.gz"));
// Write uncompressed data to GZIP output stream and it will be compressed and written to //
gziptest.gz file
gos.write(byteBuffer);
If you want buffered writing for better speed, you should wrap the
GZIPOutputStream
inside a
BufferedOutputStream
and write the data to the
BufferedOutputStream
.
BufferedOutputStream bos = new BufferedOutputStream(new GZIPOutputStream(
new FileOutputStream("gziptest.gz")));
How would you compress an object while serializing it? It is simple. Just wrap the
GZIPOutputStream
inside
an
ObjectOutputStream
object. When you write an object to your
ObjectOutputStream
, its serialized form will be
compressed using a GZIP format.
ObjectOutputStream oos = new ObjectOutputStream(new GZIPOutputStream(
new FileOutputStream("gziptest.ser")));
Apply the reverse logic to read the compressed data in GZIP format for decompressing. The following snippet of
code shows how to construct an
InputStream
object to decompress data, which is in GZIP format:
// Decompress data in GZIP format from gziptest.gz file and read it
GZIPInputStream gis = new GZIPInputStream(new FileInputStream("gziptest.gz"));
/* Read uncompressed data from GZIP input stream, e.g., gis.read(byteBuffer);*/
// Construct a BufferedInputStream to read data, which is in GZIP format
BufferedInputStream bis = new BufferedInputStream (new GZIPInputStream(
new FileInputStream(gziptest.gz")));
// Construct an ObjectInputStream to read compressed object
ObjectInputStream ois = new ObjectInputStream (new GZIPInputStream(
new FileInputStream("gziptest.ser")));
Working with JAR File Format
JAR (
J
ava
Ar
chive) is a file format based on the ZIP file format. It is used to bundle resources, class files, sound files,
images, etc. for a Java application or applet. It also provides data compression. Originally, it was developed to bundle
resources for an applet to reduce download time over an HTTP connection.