2

如何解压缩由 PHP gzcompress() 函数压缩的字符串?

有完整的例子吗?

谢谢

我现在这样尝试:

public static String unzipString(String zippedText) throws Exception
{
    ByteArrayInputStream bais = new ByteArrayInputStream(zippedText.getBytes("UTF-8"));
    GZIPInputStream gzis = new GZIPInputStream(bais);
    InputStreamReader reader = new InputStreamReader(gzis);
    BufferedReader in = new BufferedReader(reader);

    String unzipped = "";
    while ((unzipped = in.readLine()) != null) 
        unzipped+=unzipped;

    return unzipped;
}

但如果我试图解压缩 PHP gzcompress (-ed) 字符串,它就不起作用。

4

3 回答 3

9

PHP 的 gzcompress 使用 Zlib 而不是 GZIP

public static String unzipString(String zippedText) {
    String unzipped = null;
    try {
        byte[] zbytes = zippedText.getBytes("ISO-8859-1");
        // Add extra byte to array when Inflater is set to true
        byte[] input = new byte[zbytes.length + 1];
        System.arraycopy(zbytes, 0, input, 0, zbytes.length);
        input[zbytes.length] = 0;
        ByteArrayInputStream bin = new ByteArrayInputStream(input);
        InflaterInputStream in = new InflaterInputStream(bin);
        ByteArrayOutputStream bout = new ByteArrayOutputStream(512);
        int b;
        while ((b = in.read()) != -1) {
            bout.write(b); }
        bout.close();
        unzipped = bout.toString();
    }
    catch (IOException io) { printIoError(io); }
    return unzipped;
 }
private static void printIoError(IOException io)
{
    System.out.println("IO Exception: " + io.getMessage());
}
于 2011-08-05T23:35:01.310 回答
2

试试 GZIPInputStream。请参阅此示例此 SO 问题

于 2010-12-01T18:12:23.577 回答
0

http://developer.android.com/reference/java/util/zip/InflaterInputStream.html

因为 DEFLATE 算法是 gzip。

于 2010-12-01T18:11:25.017 回答