技术探索

在Android中使用GZIPInputStream解压缩数据

2015-04-24
1183

本文介绍在Android中使用GZIPInputStream进行解压缩的方法,通过测试,本方法同样适用于通过c#中的GZipStream压缩后的数据解压。参数 base64String 为压缩过的且转换为 Base64 编码后的字符串,原始字符串参用的是 UTF-8 编码。

 

public String Decompress(String base64String) throws IOException{
    byte[] t = Base64.decode(base64String, Base64.DEFAULT);
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ByteArrayInputStream in = new ByteArrayInputStream(t);
    GZIPInputStream gzip = new GZIPInputStream(in);
    try{
        byte[] buffer = new byte[4096];
        int n = 0;
        while((n = gzip.read(buffer, 0, buffer.length)) > 0){
            out.write(buffer, 0, n);
        }
    }finally{
        gzip.close();
    }
    in.close();
    out.close();
    return out.toString("UTF-8");  //还原为原始编码的字符串
}