1. 程式人生 > >字串的壓縮和解壓縮

字串的壓縮和解壓縮

http://www.blogjava.net/fastunit/archive/2008/04/25/195932.html
字串的壓縮和解壓縮
資料傳輸時,有時需要將資料壓縮和解壓縮,本例使用GZIPOutputStream/GZIPInputStream實現。

1、使用ISO-8859-1作為中介編碼,可以保證準確還原資料
2、字元編碼確定時,可以在uncompress方法最後一句中顯式指定編碼
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

// 將一個字串按照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()使用平臺預設編碼,也可以顯式的指定如toString(“GBK”)
return out.toString();
}

// 測試方法
public static void main(String[] args) throws IOException {
System.out.println(ZipUtil.uncompress(ZipUtil.compress(“中國China”)));
}

}