【问题标题】:Decompressing a string using Java.util.zip.Inflater使用 Java.util.zip.Inflater 解压缩字符串
【发布时间】:2012-03-19 12:39:45
【问题描述】:

我正在尝试解码我​​收到的字符串。 它在这里使用 deflater 压缩:https://github.com/dankogai/js-deflate 然后base64编码。

但是,当我使用 java inflater 时,我收到以下错误消息:未知压缩方法。

    import sun.misc.BASE64Decoder;

    public void org() throws Exception{
    BASE64Decoder decoder = new BASE64Decoder();

    try {      

         String inputString = "84VWAVDY";
         byte[] decodedByteArray = decoder.decodeBuffer(inputString);

         // Decompress the bytes
         Inflater decompresser = new Inflater();
         decompresser.setInput(decodedByteArray);
         byte[] result = new byte[100];

         int resultLength = decompresser.inflate(result);
         decompresser.end();

         // Decode the bytes into a String
         String outputString = new String(result, 0, resultLength);
         System.out.println("OUTPUT:" + outputString);

    } catch (Exception e){
        System.out.println("Exception: " + e);
    }
}

这段代码基本上是从 Java API 复制/粘贴的。 我也尝试过使用新的 Inflater(true);即nowrap

“注意:使用 'nowrap' 选项时,还需要提供一个额外的“虚拟”字节作为输入。这是 ZLIB 本机库要求的,以支持某些优化。”

那么这个虚拟字节应该添加到哪里呢? "byte[] decodedByteArray" 的开头还是结尾?

那么有什么想法可以解决这个问题吗?我是否只需要添加虚拟字节,是否需要使用其他方法等?

好吧,我想就是这样,感谢所有帮助!

问候

约翰

【问题讨论】:

    标签: java zlib


    【解决方案1】:

    将在末尾添加虚拟字节。然而,它只需要 zlib 1.1.4 和更早的版本。当前版本的 zlib 不需要它。我不确定 java.util.zip 使用的是什么版本的 zlib。

    【讨论】:

    • 所以要添加字节,我只需要制作另一个字节[],它比我想要添加 0 的数据长一个。然后,只需将原始数组中的字节复制到新数组中,并在最后一个单元格中添加一个 0?
    • 是的。虽然通常读取数据的原始缓冲区至少长一个字节,因此您不必进行复制。
    • OpenJDK 6 (openjdk-6-src-b27-26_oct_2012.tar.gz) 使用 zlib 1.1.3,而 OpenJDK 7 (ChangeLog) 使用 1.2.3。您可以看到 Mark 在 1.2.0 中提到的额外字节修复。
    【解决方案2】:

    “84VWAVDY”(f3 85 56 01 50 d8)的 base64 解码不是有效的原始 deflate 流,也不是有效的包装(zlib 或 gzip)deflate 流。因此,无论如何,试图夸大这些数据都不会令您满意。

    【讨论】:

    • 啊,我想这解释了很多。非常感谢!
    猜你喜欢
    • 2011-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多