I get a weird error when I try to use streamed operations to compress and decompress the String data. Exactly, the error information in Console points to 'InflaterInputStream.read()' in my 'decompress()'.
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)
However, I find it is OK if I do NOT use streamed operations in my 'compress()'. So I think the problem is due to the streamed operations. What on earth is wrong ? Can someone help me with this ?
Thanks a lot.
My code as follows:
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;
}
Find the root cause.
The content of byte array 'result' is NOT changed. So it is not work if using 'result' because the String data is not compressed actually.
The correct using is 'ByteArrayOutputStream.toByteArray()' in the 'compress()' as follows:
//btOut.close();
//return Base64.getEncoder().encodeToString(result);
return Base64.getEncoder().encodeToString(btOut.toByteArray());