Java(Android)使用gzip壓縮與解壓文件及注意事項

前言

gzip壓縮比例極大,因此使用非常廣泛,特別是網絡傳輸上,它能夠極大的減少帶寬.下面分別是壓縮和解壓縮的測試代碼及相應注意事項.


源碼

package android.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class Gzip {
	
	//壓縮
	public static byte[] compress(String str, String encoding){
		if(str == null || str.length() == 0){
			return null;
		}
		
		ByteArrayOutputStream outs = new ByteArrayOutputStream();
		GZIPOutputStream gzip;
		byte[] compressRes = null;
		try {
			gzip = new GZIPOutputStream(outs);
			byte[] tmpBytes = str.getBytes(encoding);   
			gzip.write(tmpBytes);
			gzip.close();
			compressRes = outs.toByteArray();  //一定要放在gzip.close()之後
			outs.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return compressRes;
	}

	//解壓
	public static byte[] uncompress(byte[] uncompressSource){
		if(uncompressSource == null || uncompressSource.length == 0){
			return null;
		}
		
		ByteArrayOutputStream outs = new ByteArrayOutputStream();
		ByteArrayInputStream ins = new ByteArrayInputStream(uncompressSource);
		GZIPInputStream ungzip;
		byte[] uncompressRes = null;
		try {
			ungzip = new GZIPInputStream(ins);
			byte[] buff = new byte[1024];
			int n = 0;
			while((n = ungzip.read(buff)) >= 0){
				outs.write(buff, 0, n);
			}
			ungzip.close();
			uncompressRes = outs.toByteArray(); //這個放在ungzip.close()前也可以
			ins.close();
			outs.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return uncompressRes;
	}
}
*注意事項:在壓縮的時候,需要先將壓縮流關閉,再把壓縮結果字符流導出,不然會導致壓縮失敗;而解壓則無此種順序問題.
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章