开发者

Java: Is there a way to get the expected uncompressed length of a zipped byte array?

开发者 https://www.devze.com 2023-03-09 05:22 出处:网络
I\'m using java.util.zip to compress and uncompress byte arrays, using Inflater and Deflater. Does the compressed result contain information about the expected length of the original data or do I ha

I'm using java.util.zip to compress and uncompress byte arrays, using Inflater and Deflater.

Does the compressed result contain information about the expected length of the original data or do I have to store it myself?

I would like to know the expected length of t开发者_开发技巧he uncompressed information without uncompressing all of the data.


If you just compress and decompress byte arrays - without storing them in a ZipEntry - you must save the size yourself, as the byte array to which you compress the data is not necessarily used to its full extent.

You can see this clearly from the example in Deflater's 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, 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
 }

The code must maintain the compressed data's lenght as the output array is of length 100, no matter the actual length of the data it stores.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号