【问题标题】:gzinflate in JavaJava中的gzinflate
【发布时间】:2012-07-09 02:31:33
【问题描述】:

所以,我的 Java 应用程序接收了一些使用 PHP 的 gzdeflate() 生成的数据。 现在我正在尝试用 Java 扩充这些数据。这是我到目前为止所得到的:

InflaterInputStream inflInstream = new InflaterInputStream(new ByteArrayInputStream(inputData.getBytes() ), new Inflater());

byte bytes[] = new byte[1024];
while (true) {
    int length = inflInstream.read(bytes, 0, 1024);
    if (length == -1)  break;

    System.out.write(bytes, 0, length);
}

'inputData' 是一个包含压缩数据的字符串。

问题是:.read方法抛出异常:

java.util.zip.ZipException:标头检查不正确

关于这个主题的其他网站只会将我重定向到 Inflater 类的文档,但显然我不知道如何使用它来与 PHP 兼容。

【问题讨论】:

    标签: java php interop zlib


    【解决方案1】:

    根据documentation,php gzdeflate() 生成原始 deflate 数据 (RFC 1951),但 Java 的 Inflater class 需要 zlib (RFC 1950) 数据,这是包装在 zlib 标头和尾部的原始 deflate 数据。 除非您将nowrap as true 指定给Inflater 构造函数。然后它将解码原始 deflate 数据。

    InputStream inflInstream = new InflaterInputStream(new ByteArrayInputStream(inputData.getBytes()), 
                                                       new Inflater(true));
    
    byte bytes[] = new byte[1024];
    while (true) {
        int length = inflInstream.read(bytes, 0, 1024);
        if (length == -1)  break;
    
        System.out.write(bytes, 0, length);
    }
    

    【讨论】:

      【解决方案2】:

      按照示例使用 GZIPInputStream(不要直接使用 Inflater):

      http://java.sun.com/developer/technicalArticles/Programming/compression/

      【讨论】:

      • 那行不通我现在将第一行更改为 InputStream inflInstream = new GZIPInputStream(new ByteArrayInputStream( inputData.getBytes() ));这会导致 java.util.zip.ZipException: Not in GZIP 格式。
      • 将数据保存到文件中并使用一些ZIP工具打开它,并验证格式...
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-27
      • 2011-08-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-22
      相关资源
      最近更新 更多