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

發佈了37 篇原創文章 · 獲贊 5 · 訪問量 13萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章