Android: decompress string that was compressed with PHP gzcompress()

梦想的初衷 提交于 2019-12-30 05:30:08

问题


How can i decompress a String that was zipped by PHP gzcompress() function?

Any full examples?

thx

I tried it now like this:

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

but it's not working if i i'm trying to unzip a PHP gzcompress (-ed) string.


回答1:


PHP's gzcompress uses Zlib NOT 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());
}



回答2:


Try a GZIPInputStream. See this example and this SO question.




回答3:


See

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

since the DEFLATE algorithm is gzip.



来源:https://stackoverflow.com/questions/4327517/android-decompress-string-that-was-compressed-with-php-gzcompress

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