流式操作出现错误 'java.util.zip.ZipException: incorrect header check'

Streamed operations get the error 'java.util.zip.ZipException: incorrect header check'

当我尝试使用流操作来压缩和解压缩字符串数据时,出现了一个奇怪的错误。 正好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;
}

找到根本原因。

字节数组'result'的内容没有改变。所以如果使用 'result' 是行不通的,因为字符串数据实际上没有被压缩。

在'compress()'中正确的用法是'ByteArrayOutputStream.toByteArray()'如下:

//btOut.close();
//return Base64.getEncoder().encodeToString(result);

return Base64.getEncoder().encodeToString(btOut.toByteArray());