如何解决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,无论它存储的数据的实际长度如何。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。