字符串的壓縮和解壓縮


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")));
}

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM