当前位置: 移动技术网 > IT编程>移动开发>Android > GZIP压缩与解压

GZIP压缩与解压

2019年01月09日  | 移动技术网IT编程  | 我要评论

限韩令原因,达杜拉康德,爱情保卫战奇葩女

public class gzip {
    /**
     * 字符串的压缩
     * 
     * @param str
     *            待压缩的字符串
     * @return 返回压缩后的字符串
     * @throws ioexception
     */
    public static string compress(string str) throws ioexception {
        if (null == str || str.length() <= 0) {
            return str;
        }
        // 创建一个新的输出流
        bytearrayoutputstream out = new bytearrayoutputstream();
        // 使用默认缓冲区大小创建新的输出流
        gzipoutputstream gzip = new gzipoutputstream(out);
        // 将字节写入此输出流
        gzip.write(str.getbytes("utf-8")); // 因为后台默认字符集有可能是gbk字符集,所以此处需指定一个字符集
        gzip.close();
        // 使用指定的 charsetname,通过解码字节将缓冲区内容转换为字符串
        return out.tostring("iso-8859-1");
    }

    /**
     * 字符串的解压
     * 
     * @param str
     *            对字符串解压
     * @return 返回解压缩后的字符串
     * @throws ioexception
     */
    public static string uncompress(string str) throws ioexception {
        if (null == str || str.length() <= 0) {
            return str;
        }
        // 创建一个新的输出流
        bytearrayoutputstream out = new bytearrayoutputstream();
        // 创建一个 bytearrayinputstream,使用 buf 作为其缓冲区数组
        bytearrayinputstream in = new bytearrayinputstream(str.getbytes("iso-8859-1"));
        // 使用默认缓冲区大小创建新的输入流
        gzipinputstream gzip = new gzipinputstream(in);
        byte[] buffer = new byte[256];
        int n = 0;

        // 将未压缩数据读入字节数组
        while ((n = gzip.read(buffer)) >= 0) {
            out.write(buffer, 0, n);
        }
        // 使用指定的 charsetname,通过解码字节将缓冲区内容转换为字符串
        return out.tostring("utf-8");
    }
    
    
    public static void main(string[] args) throws ioexception {
        string str="看甲方时点击翻身肯\n";  //内容大小控制在240byte, >240 进行压缩·否则不压··
        system.out.println("原文大小:"+str.getbytes().length+" \n压缩前:"+str);
        
        string compress = gzip.compress(str);
        system.out.println("解压大小:"+compress.getbytes().length+" \n压缩后:"+compress);
        
        string uncompress = gzip.uncompress(compress);
        system.out.println("解压大小:"+uncompress.getbytes().length+" \n解压缩:"+uncompress);
    }
}

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网