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:

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.


If you enjoy this Java programming article, please share with friends and colleagues. Follow the author on Twitter for the latest news and rants.

Editorial page content written by Neil Coffey. Copyright © Javamex UK 2021. All rights reserved.