Java:有没有办法获得压缩字节数组的预期未压缩长度?

时间:2011-05-31 11:17:47

标签: java zip

我正在使用java.util.zip使用InflaterDeflater来压缩和解压缩字节数组。

压缩结果是否包含有关原始数据的预期长度的信息,还是我必须自己存储?

我想知道未压缩信息的预期长度而不解压缩所有数据。

1 个答案:

答案 0 :(得分:0)

如果只压缩和解压缩字节数组 - 而不将它们存储在ZipEntry中 - 您必须自己保存大小,因为压缩数据的字节数组不一定完全用于其中。< / p>

您可以在Deflater的{​​{3}}:

中的示例中清楚地看到这一点
try {
     // Encode a String into bytes
     String inputString = "blahblahblah??";
     byte[] input = inputString.getBytes("UTF-8");

     // Compress the bytes
     byte[] output = new byte[100];
     Deflater compresser = new Deflater();
     compresser.setInput(input);
     compresser.finish();
     int compressedDataLength = compresser.deflate(output);

     // Decompress the bytes
     Inflater decompresser = new Inflater();
     decompresser.setInput(output, 0, compressedDataLength);
     byte[] result = new byte[100];
     int resultLength = decompresser.inflate(result);
     decompresser.end();

     // Decode the bytes into a String
     String outputString = new String(result, 0, resultLength, "UTF-8");
 } catch(java.io.UnsupportedEncodingException ex) {
     // handle
 } catch (java.util.zip.DataFormatException ex) {
     // handle
 }

代码必须保持压缩数据的长度,因为输出数组的长度为100,无论它存储的数据的实际长度如何。