Java - compression size output-byteArray

When using the deflate method for java.util.zip.Deflater, byte [] must be specified as an argument, how large should this byte [] be initialized? I did not read any guarantee there that the compressed data will be even smaller than the uncompressed data. Is there a certain percentage of input I have to go with? I am currently doing this twice as large as the input

+5
source share
2 answers

After the deflatecall finished, call to find out if he has more to display. eg:

byte[] buffer = new byte[BUFFER_SIZE];
while (!deflater.finished()) {
  int n = deflater.deflate(buffer);
  // deal with the n bytes in out here
}

If you just want to collect all the bytes in memory, you can use ByteArrayOutputStream. eg:

byte[] buffer = new byte[BUFFER_SIZE];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while (!deflater.finished()) {
  int n = deflater.deflate(buffer);
  baos.write(buffer, 0, n);
}
return baos.toByteArray();
+8

Java "deflater"? "". Jeez! , .

, , deflate, . , , , . zlib, Java, , deflateBound(), . , , :

complen = sourceLen +
          ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 5;
+6

All Articles