java - 流式操作收到错误“java.util.zip.ZipException:不正确的标头检查”
问题描述
当我尝试使用流式操作来压缩和解压缩字符串数据时,我得到一个奇怪的错误。确切地说,Console 中的错误信息指向我的“decompress()”中的“InflaterInputStream.read()”。
java.util.zip.ZipException: incorrect header check
at java.util.zip.InflaterInputStream.read(InflaterInputStream.java:164)
at java.util.zip.InflaterInputStream.read(InflaterInputStream.java:122)
at mytest.decorator.demo.CompressionDecorator.decompress(CompressionDecorator.java:98)
但是,我发现如果我不在我的 'compress()' 中使用流式操作是可以的。所以我认为问题是由于流式操作。到底怎么了?有人可以帮我弄这个吗 ?
非常感谢。
我的代码如下:
private String compress(String strData) {
byte[] result = strData.getBytes();
Deflater deflater = new Deflater(6);
boolean useStream = true;
if (!useStream) {
byte[] output = new byte[128];
deflater.setInput(result);
deflater.finish();
int compressedDataLength = deflater.deflate(output);
deflater.finished();
return Base64.getEncoder().encodeToString(output);
}
else {
ByteArrayOutputStream btOut = new ByteArrayOutputStream(128);
DeflaterOutputStream dfOut = new DeflaterOutputStream(btOut, deflater);
try {
dfOut.write(result);
dfOut.close();
btOut.close();
return Base64.getEncoder().encodeToString(result);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
private String decompress(String strData) {
byte[] bts = Base64.getDecoder().decode(strData);
ByteArrayInputStream bin = new ByteArrayInputStream(bts);
InflaterInputStream infIn = new InflaterInputStream(bin);
ByteArrayOutputStream btOut = new ByteArrayOutputStream(128);
try {
int b = -1;
while ((b = infIn.read()) != -1) {
btOut.write(b);
}
bin.close();
infIn.close();
btOut.close();
return new String(btOut.toByteArray());
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
解决方案
找到根本原因。
字节数组“结果”的内容没有改变。所以如果使用“结果”是行不通的,因为字符串数据实际上没有被压缩。
正确使用是 'compress()' 中的 'ByteArrayOutputStream.toByteArray()' 如下:
//btOut.close();
//return Base64.getEncoder().encodeToString(result);
return Base64.getEncoder().encodeToString(btOut.toByteArray());
推荐阅读
- javascript - 如何从 base64 javascript 创建视频元素?
- python - 在pandas读取csv函数中推断日期时间格式时如何保持数据帧索引的时区?
- reactjs - React Accordion 中的复选框在 IE Spring Boot 应用程序中不起作用
- python - 如果参数大于长度,如何使 nlargest 函数出错
- python - 如何获取一个字符串并将其用作调用函数的标识符?
- python - 我怎样才能使这段代码工作?,我使用beautifulsoup4,我无法将该值刮到csv文件中
- java - 如何使用 IntelliJ 将外部文件夹添加到源代码?
- string - 使用 pySpark 提取字符串
- c++ - 如何将视频从 sys1 逐帧流式传输到 sys2 上的 qt 应用程序并在 linux 上实时显示
- sql - SQL:尝试 SELECT COUNT 一列并同时显示另一列