javacompressiongzipdeflate

Does `deflate` always compress your entire block?


Here's example from the documentation:

 byte[] output = new byte[100];
 Deflater compresser = new Deflater();
 compresser.setInput(input);
 compresser.finish();
 int compressedDataLength = compresser.deflate(output);
 compresser.end();

but DeflaterOutputStream does this:

        if (!def.finished()) {
            def.setInput(b, off, len);
            while (!def.needsInput()) {
                 int len = def.deflate(buf, 0, buf.length);
                 if (len > 0) {
                 out.write(buf, 0, len);
               }
            }
        }

which makes me think that just because you've gotten a non-zero return from a call to deflate() does not mean that your entire input was compressed.

Is this correct? In the documentation, I'm having trouble finding where this is explicitly mentioned.


Solution

  • It will not have finished if you didn't give it enough output space. You need to keep calling deflate() with more output space until finished() is true.

    Note that it will never report that it finished if you didn't tell it that you have provided all of the input with finish(). Which the example does.