Home  Java compression intro  Deflater how-to  Deflater algorithm  Deflater configuration  Text compression performance  GZIP files  ZIP files

Search this site:
Threads Database Profiling Regular expressions Random numbers Compression Exceptions C Equivalents in Java

How to use the Deflater class

Before looking in detail at what the Java Deflater actually does, let's jump straight in and see how to use it. In practice, compression with Deflater works as follows:

  • We have the data that we want to compress in a byte array, or in some other form that we can write to a stream;
  • We have an OutputStream that we want to write the compressed data to;
  • We construct a Deflater object;
  • We construct a DeflaterOutputStream around the output stream that we want to write the data to, initialising it with our Deflater object.

Once we've constructed our DeflaterOutputStream, we can write our uncompressed data to it just as we would to any old output stream. Here is what things look like in Java code:

public void compressData(byte[] data, OutputStream out)
    throws IOException {
  Deflater d = new Deflater();
  DeflaterOuptutStream dout = new DeflaterOutputStream(out, d);
  dout.write(data);
  dout.close();
}

We don't actually have to explicitly pass in a Deflater to the constructor of DeflaterOutputStream: if we just pass in the stream, then a default deflater will be constructed for us. However, we'll see in a moment that we may wish to pass certain parameters to the Deflater when constructing it.

Data decompression

Decompressing the data "on the other end" uses the Inflater class, usually inside an InflaterInputStream:

public byte[] decompressData(InputStream in)
    throws IOException {
  InflaterInputStream in = new InflaterInputStream(in);
  ByteArrayOutputStream bout =
    new ByteArrayOutputStream(512);
  int b;
  while ((b = in.read()) != -1) {
    bout.write(b);
  }
  in.close();
  bout.close();
  return bout.toByteArray();
}

If you don't have much time to spare and your data is fairly typical, then this is about all you need to know to get started with data compression in Java.

However, if you have development time available, you may find some benefit in (a) understanding how deflate works and (b) configuring the Deflater and transforming your data to take best advantage of it.

comments powered by Disqus

Written by Neil Coffey. Copyright © Javamex UK 2012. All rights reserved.