【发布时间】:2021-02-18 10:51:14
【问题描述】:
当我尝试使用流式操作来压缩和解压缩字符串数据时,我遇到了一个奇怪的错误。 确切地说,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;
}
【问题讨论】:
标签: java compression zipexception