【通讯】采用ZLIB实现传输过程的数据压缩
Posted on Mon 16 June 2008 in 我用(IT)
- 关于ZLIB
zlib是提供数据压缩的一个函数库,使用抽象化的DEFLATE演算法。
zlib是开源的,做为一种事实上的业界标准,因其代码的可移植性,宽松的授權许可以及较小的内存占用,zlib在许多嵌入式设备中也有应用。
http://en.wikipedia.org/wiki/ZLIB
- 代码示意
/**
*
* Put Object to compressed Byte Array
*
*/
protected byte[] deflate(Object object) throws IOException{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Deflater def = new Deflater (Deflater.BEST_COMPRESSION);
DeflaterOutputStream dos = new DeflaterOutputStream(baos, def);
ObjectOutputStream out = new ObjectOutputStream(dos);
out.writeObject(object);
out.close();
dos.finish();
dos.close();
return baos.toByteArray();
}
/**
*
* Read Object from compressed Byte Array
*
*/
protected Object inflate(byte[] compressedContent) throws IOException{
if(compressedContent == null)
return null;
try{
ObjectInputStream in = new ObjectInputStream(
new InflaterInputStream(new ByteArrayInputStream(compressedContent)));
Object object = in.readObject();
in.close();
return object;
}catch(Exception e){
throw new IOException(e.toString());
}
}