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

问题描述

| 我正在使用
java.util.zip
Inflater
Deflater
来压缩和解压缩字节数组。 压缩结果是否包含有关原始数据预期长度的信息,还是我必须自己存储? 我想知道未压缩信息的预期长度,而不需要解压缩所有数据。     

解决方法

        如果仅压缩和解压缩字节数组(而不将其存储在“ 3”中),则必须自己保存大小,因为压缩数据的字节数组并不一定会用完。 您可以从
Deflater
的javadoc中的示例清楚地看到这一点:
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,compressedDataLength);
     byte[] result = new byte[100];
     int resultLength = decompresser.inflate(result);
     decompresser.end();

     // Decode the bytes into a String
     String outputString = new String(result,resultLength,\"UTF-8\");
 } catch(java.io.UnsupportedEncodingException ex) {
     // handle
 } catch (java.util.zip.DataFormatException ex) {
     // handle
 }
该代码必须保持压缩数据的长度,因为输出数组的长度为100,无论它存储的数据的实际长度如何。