Java 解压 Node.js DeflaterRaw 压缩的字符串 报无标头解决方案

前端 Node.js DeflaterRaw 压缩zipJSON字符串,是没有标头的!

所以使用Java inflater 去解压时会报,提示无标头异常! incorrect header check!

java.util.zip.DataFormatException: incorrect header check
	at java.util.zip.Inflater.inflateBytes(Native Method)
	at java.util.zip.Inflater.inflate(Inflater.java:259)
	at java.util.zip.Inflater.inflate(Inflater.java:280)
	at com.example.my_qr_smart.ExampleUnitTest.decompressStrToBytes(ExampleUnitTest.java:68)

此时我们要使用Java inflater 去解压字符串时需要将Inflater 的 nowrap 设置为 true 去忽略标头进行解压即可。

     public static String compressStrToBytes(byte[] str) throws IOException {
        byte[] outinput = new byte[0];

        Inflater decompresser = new Inflater(true); //设置为Ture
        decompresser.reset();
        decompresser.setInput(str);

        ByteArrayOutputStream out = new ByteArrayOutputStream(str.length);
        try {
            byte[] buf = new byte[1024];
            while (!decompresser.finished()) {
                int i = decompresser.inflate(buf);
                out.write(buf, 0, i);
            }
            outinput = out.toByteArray();
        } catch (Exception e) {
            outinput = str;
            e.printStackTrace();
        } finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        decompresser.end();
        return new String(outinput);
    }

更改后就可以正常解压输出。
在这里插入图片描述

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐