Configuring a Deflater

On the previous page, we saw how to use a Deflater to compress data in Java (and how to read the compressed data back in again). We mentioned that the reason for explicitly constructing the Deflater object separately to the DeflaterOutputStream is that in this way, the Deflater can be configured. The main two parameters that we can configure are as follows:

Compression level

In our discussion of how the Deflater works, we saw that a key part is dictionary compression. In this type of compression, the compressor looks for previously-occurring sequences that are the same as the sequence about to be encoded.

When constructing a Deflater, you can specify a compression level value, from 1 to 9. The compression level, roughly speaking, defines how rigorously the compressor looks to find the longest string possible. As a general rule of thumb:

You have to decide whether, for your application, the extra processor time is worth the extra few per cent of compression.

Compression strategy

Generally speaking, it will not be necessary to change the compression strategy. However, in certain advanced cases, you can actually improve compression by transforming your data so that Huffman encoding works better on it. In such cases, we'll see that explicitly specifying the FILTERED or HUFFMAN_ONLY strategy can be beneficial.


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.