使用Java.util.zip.Inflater解压缩字符串

时间:2012-03-19 12:39:45

标签: java zlib

我正在尝试解码收到的字符串。 它是使用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(真实);即现在的

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

那么这个虚拟字节应该添加到哪里?在“byte [] decodingByteArray”的开头或结尾处??

那么任何想法如何解决这个问题?我只需要添加虚拟字节,是否需要使用其他一些方法等?

嗯,我想是的,所有的帮助都表示赞赏!

此致

约翰

2 个答案:

答案 0 :(得分:4)

最后会添加虚拟字节。但是,只有zlib 1.1.4及更早版本才需要它。 zlib的当前版本不需要它。我不确定java.util.zip使用的是什么版本的zlib。

答案 1 :(得分:4)

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