Java - How to compress using deflater with dynamic byte size

232 Views Asked by At

How to compress byte array using deflater? I tried with deflate inflate example from Oracle page. It worked fine.

My doubt is how to make byte[] size dynamic.? And how to calculate before and after compression of byte[]?

1

There are 1 best solutions below

0
s.fuhrm On

The API is a bit confusing. Take a look at finished() which tells you after attempting to compress into a too-small buffer that it was too small.

Your only chance to go on is either

  • incrementally increasing the buffer if finished()==false and/or
  • starting with a sufficient big buffer (that might be too small also).

One alternative could be using DeflaterOutputStream writing into a ByteArrayOutputStream, but that's much more high-level than the approach you were asking for.