【问题标题】:Streamed operations get the error 'java.util.zip.ZipException: incorrect header check'流式操作收到错误“java.util.zip.ZipException:不正确的标头检查”
【发布时间】: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


    【解决方案1】:

    找到根本原因。

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

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

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

    【讨论】:

      猜你喜欢
      • 2013-03-06
      • 2019-11-29
      • 2013-03-19
      • 2018-12-13
      • 2021-08-31
      • 2015-09-21
      • 1970-01-01
      • 2015-05-29
      • 2015-09-25
      相关资源
      最近更新 更多