Dave Bakker
Dave Bakker

Reputation: 143

gzinflate in Java

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.

Upvotes: 3

Views: 6863

Answers (2)

Mark Adler
Mark Adler

Reputation: 112412

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);
}

Upvotes: 11

gliptak
gliptak

Reputation: 3670

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

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

Upvotes: 1

Related Questions