Deflater 和 Inflater 的用法

Deflater 是用于压缩数据包的,当数据包比较大的时候,采用压缩后的数据,可以减少带宽的占用,加多传送的
速度,Inflater则时对压缩后的数据包解压用的。先看看jdk中的example
// Encode a String into bytes ,Deflater和Inflater只能对byte[]型的数据处理,所以要先转成byte[]型
String inputString = "blahblahblah??";
byte[] input = inputString.getBytes("UTF-8");

// Compress the bytes 开始压缩数据, 
byte[] output = new byte[100];
Deflater compresser = new Deflater();
compresser.setInput(input); // 要压缩的数据包
compresser.finish(); // 完成, 
int compressedDataLength = compresser.deflate(output); // 压缩,返回的是数据包经过缩缩后的大小

// Decompress the bytes // 开始解压,
Inflater decompresser = new Inflater();
decompresser.setInput(output, 0, compressedDataLength); 
// 对byte[]进行解压,同时可以要解压的数据包中的某一段数据,就好像从zip中解压出某一个文件一样。
byte[] result = new byte[100];
int resultLength = decompresser.inflate(result); // 返回的是解压后的的数据包大小,
decompresser.end();

// Decode the bytes into a String
String outputString = new String(result, 0, resultLength, "UTF-8");


最好可以看看 GZIPInputStream 和 GZIPOutputStream, 
这两个类用于读入和写出GZIP文件格式的(压缩和解压) 的数据流, 就是说可以在server端用这两个类传送压缩后
的数据包,而不用再用上面的两个类再处理一次。
in = new GZIPInputStream( this.getInputStream(), 4096 );
out = new GZIPOutputStream( client.getOutputStream(), 4096 );

 

源地址:http://cwq.yfjhh.com/2008/06/javadeflaterinflater.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值