數(shù)據(jù)傳輸時(shí),有時(shí)需要將數(shù)據(jù)壓縮和解壓縮,本例使用GZIPOutputStream/GZIPInputStream實(shí)現(xiàn)。
1、使用ISO-8859-1作為中介編碼,可以保證準(zhǔn)確還原數(shù)據(jù)
2、字符編碼確定時(shí),可以在uncompress方法最后一句中顯式指定編碼
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
// 將一個(gè)字符串按照zip方式壓縮和解壓縮
public class ZipUtil {
// 壓縮
public static String compress(String str) throws IOException {
if (str == null || str.length() == 0) {
return str;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(out);
gzip.write(str.getBytes());
gzip.close();
return out.toString("ISO-8859-1");
}
// 解壓縮
public static String uncompress(String str) throws IOException {
if (str == null || str.length() == 0) {
return str;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteArrayInputStream in = new ByteArrayInputStream(str
.getBytes("ISO-8859-1"));
GZIPInputStream gunzip = new GZIPInputStream(in);
byte[] buffer = new byte[256];
int n;
while ((n = gunzip.read(buffer)) >= 0) {
out.write(buffer, 0, n);
}
// toString()使用平臺(tái)默認(rèn)編碼,也可以顯式的指定如toString("GBK")
return out.toString();
}
// 測試方法
public static void main(String[] args) throws IOException {
System.out.println(ZipUtil.uncompress(ZipUtil.compress("中國China")));
}
}