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

你可能感兴趣的:(java)