首页 > 解决方案 > 流式操作收到错误“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;
}

标签: javacompressionzipexception

解决方案


找到根本原因。

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

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

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

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

推荐阅读