Deflater 和 Inflater 在java中的用法以及注意的参数问题

项目中用到了这个压缩和解压缩的方式,与服务器端的压缩算法相对应,客户端是android,数据压缩后通过webservice传递到服务器(php),一开始怎么压缩数据都无法再服务器端解压,一直困扰了很久,偶然间在国外的网站上找到一个说明,是创建对象的flag有true和false,分别对应两个版本的协议,最后通用的(和php服务器端的解压缩对应)应该是把flag设置为true。下面代码记录了调用方式,需要注意创建两个对象的参数。

压缩端

    public static byte[] compressBytes(byte[] byteStr) {
ByteArrayInputStream bis = new ByteArrayInputStream(byteStr);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {

                        // 此处的第二个参数必须要设置成true,这样才能成功与服务器端对应压缩与解压缩(服务器端对应的是php的解压缩)

                       // 具体的原因是参照网上说的一个协议。参照地址以后会补发上来
Deflater def = new Deflater(Deflater.BEST_COMPRESSION,true);
DeflaterOutputStream dos = new DeflaterOutputStream(bos, def);
byte[] buf = new byte[1024];
int readCount = 0;
while ((readCount = bis.read(buf, 0, buf.length)) > 0) {
dos.write(buf, 0, readCount);
}
dos.close();
} catch (Exception ex) {
ex.printStackTrace();
}
byte[] res = bos.toByteArray();
return res;
}

 解压缩

   public static byte[] decompressBytes(byte[] byteEncrypto) {
ByteArrayInputStream bis = new ByteArrayInputStream(byteEncrypto);
ByteArrayOutputStream bos = new ByteArrayOutputStream();

                // 相对应的解压缩的参数也要设置未true
Inflater inf = new Inflater(true);
InflaterInputStream iis = new InflaterInputStream(bis, inf);
int readCount = 0;
byte[] buf = new byte[1024];
try {
while ((readCount = iis.read(buf, 0, buf.length)) > 0) {
bos.write(buf, 0, readCount);
}
iis.close();
return bos.toByteArray();
} catch (ZipException e) {
} catch (IOException e) {
e.printStackTrace();
}
return null;
}

  希望对用到的有点帮助,可能这个压缩算法在国内用的比较少,中文网站一直没找到有详细解释的。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值