项目中用到了这个压缩和解压缩的方式,与服务器端的压缩算法相对应,客户端是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;
}
希望对用到的有点帮助,可能这个压缩算法在国内用的比较少,中文网站一直没找到有详细解释的。