2

I wrote some Javascript code. compress with base64 and deflate

function base64 (str) {
    return new Buffer(str).toString("base64");
}

function deflate (str) {
    return RawDeflate.deflate(str);
}

function encode (str) {
    return base64(deflate(str));
}
var str = "hello, world";
console.log("Test Encode");
console.log(encode(str));

I converted "hello, world" to 2f8d48710d6e4229b032397b2492f0c2

and I want to decompress this string(2f8d48710d6e4229b032397b2492f0c2) in java

I put the str in a file, then:

public static String decompress1951(final String theFilePath) {
    byte[] buffer = null;

    try {
        String ret = "";
        System.out.println("can come to ret");

        InputStream in = new InflaterInputStream(new Base64InputStream(new FileInputStream(theFilePath)), new Inflater(true));
        System.out.println("can come to in");
        while (in.available() != 0) {
            buffer = new byte[20480];
*****line 64 excep happen            int len = in.read(buffer, 0, 20480);
            if (len <=0) {
                break;
            }
            ret = ret + new String(buffer, 0, len);
        }
        in.close();
        return ret;

    } catch (IOException e) {
        System.out.println("Has IOException");
        System.out.println(e.getMessage());

        e.printStackTrace();
    }
    return "";
}

But I have an exception:

java.util.zip.ZipException: invalid stored block lengths
    at java.util.zip.InflaterInputStream.read(Unknown Source)
    at com.cnzz.mobile.datacollector.DecompressDeflate.decompress1951(DecompressDeflate.java:64)
    at com.cnzz.mobile.datacollector.DecompressDeflate.main(DecompressDeflate.java:128)
demongolem
  • 9,474
  • 36
  • 90
  • 105
littletiger
  • 651
  • 1
  • 8
  • 14
  • The code is right The key point is the second parameter of InflaterInputStream new Inflater(true). Without this parameter,the code can work,but is not the pure defalter. Maybe is diff with the RFC1950 zlib:[basic links](http://www.ietf.org/rfc/rfc1950.txt). (without) RFC 1951 deflate:[basic links](http://www.ietf.org/rfc/rfc1951.txt). (with new Inflater(true)) And the converted string of "hello, world" is not 2f8d48710d6e4229b032397b2492f0c2. That's why I cannot solve it – littletiger Feb 01 '12 at 11:27

1 Answers1

0

The java code up there works perfectly. As in the comment, you somehow got the encoded value wrong. The encoded value I got using the javascript value is y0jNycnXUSjPL8pJAQA=

Then, when you copy this value to file and call decompress1951, you do in fact get back hello, world as required. Don't know what to say on the javascript part as the code you use seems to sync up nicely with examples on the distribution web pages. I notice there is the original and the fork so maybe there is some confusion there? Anyhow there is this jsfiddle which I think can be seen as a working version if you want to take a look at that one.

demongolem
  • 9,474
  • 36
  • 90
  • 105