gzinflate in Java

流过昼夜 提交于 2021-02-08 04:38:22

问题


So, my Java application reveives some data that is generated with PHP's gzdeflate(). Now i'm trying to inflate that data with Java. This is what i've got so far:

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' is a String containing the deflated data.

The problem is: the .read method throws an exception:

java.util.zip.ZipException: incorrect header check

Other websites on this subject only go as far as redirecting me to the Inflater class' documentation, but apparently I don't know how to use it to be compatible with PHP.


回答1:


Per the documentation, php gzdeflate() generates raw deflate data (RFC 1951), but Java's Inflater class is expecting zlib (RFC 1950) data, which is raw deflate data wrapped in zlib header and trailer. Unless you specify nowrap as true to the Inflater constructor. Then it will decode raw deflate data.

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:


Use the GZIPInputStream as per examples at (do not use the Inflater directly):

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



来源:https://stackoverflow.com/questions/11399350/gzinflate-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!