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;
	}
}
*注意事项:在压缩的时候,需要先将压缩流关闭,再把压缩结果字符流导出,不然会导致压缩失败;而解压则无此种顺序问题.

你可能感兴趣的:(Java)