Java decompressing array of bytes

2019-02-25 23:15发布

On server (C++), binary data is compressed using ZLib function:

compress2()

and it's sent over to client (Java). On client side (Java), data should be decompressed using the following code snippet:

public static String unpack(byte[] packedBuffer) {
    InflaterInputStream inStream = new InflaterInputStream(new ByteArrayInputStream( packedBuffer);
    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    int readByte;
    try {
        while((readByte = inStream.read()) != -1) {
            outStream.write(readByte);
        }
    } catch(Exception e) {
        JMDCLog.logError(" unpacking buffer of size: " + packedBuffer.length);
        e.printStackTrace();
    // ... the rest of the code follows
}

Problem is that when it tries to read in while loop it always throws:

java.util.zip.ZipException: invalid stored block lengths

Before I check for other possible causes can someone please tell me can I compress on one side with compress2 and decompress it on the other side using above code, so I can eliminate this as a problem? Also if someone has a possible clue about what might be wrong here (I know I didn't provide too much of of the code in here but projects are rather big.

Thanks.

标签: java zip gzip zlib
2条回答
放荡不羁爱自由
2楼-- · 2019-02-25 23:50

I think the problem is not with unpack method but in packedBuffer content. Unpack works fine

public static byte[] pack(String s) throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    DeflaterOutputStream dout = new DeflaterOutputStream(out);
    dout.write(s.getBytes());
    dout.close();
    return out.toByteArray();
}

public static void main(String[] args) throws Exception {
    byte[] a = pack("123");
    String s = unpack(a);   // calls your unpack
    System.out.println(s);
}

output

123
查看更多
不美不萌又怎样
3楼-- · 2019-02-26 00:05

InflaterInputStream is expecting raw deflate data (RFC 1951), whereas compress2() is producing zlib-wrapped deflate data (RFC 1950 around RFC 1951).

Inflater on the other hand does process zlib-wrapped data (unless you give it the nowrap option). Go figure.

查看更多
登录 后发表回答