Android GZIP压缩与解压
生活随笔
收集整理的這篇文章主要介紹了
Android GZIP压缩与解压
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
public class GZIP {
/**
* 字符串的壓縮
*
* @param str
* 待壓縮的字符串
* @return 返回壓縮后的字符串
* @throws IOException
*/
public static String compress(String str) throws IOException {
if (null == str || str.length() <= 0) {
return str;
}
// 創(chuàng)建一個新的輸出流
ByteArrayOutputStream out = new ByteArrayOutputStream();
// 使用默認(rèn)緩沖區(qū)大小創(chuàng)建新的輸出流
GZIPOutputStream gzip = new GZIPOutputStream(out);
// 將字節(jié)寫入此輸出流
gzip.write(str.getBytes("utf-8")); // 因?yàn)楹笈_默認(rèn)字符集有可能是GBK字符集,所以此處需指定一個字符集
gzip.close();
// 使用指定的 charsetName,通過解碼字節(jié)將緩沖區(qū)內(nèi)容轉(zhuǎn)換為字符串
return out.toString("ISO-8859-1");
}
/**
* 字符串的解壓
*
* @param str
* 對字符串解壓
* @return 返回解壓縮后的字符串
* @throws IOException
*/
public static String unCompress(String str) throws IOException {
if (null == str || str.length() <= 0) {
return str;
}
// 創(chuàng)建一個新的輸出流
ByteArrayOutputStream out = new ByteArrayOutputStream();
// 創(chuàng)建一個 ByteArrayInputStream,使用 buf 作為其緩沖區(qū)數(shù)組
ByteArrayInputStream in = new ByteArrayInputStream(str.getBytes("ISO-8859-1"));
// 使用默認(rèn)緩沖區(qū)大小創(chuàng)建新的輸入流
GZIPInputStream gzip = new GZIPInputStream(in);
byte[] buffer = new byte[256];
int n = 0;
// 將未壓縮數(shù)據(jù)讀入字節(jié)數(shù)組
while ((n = gzip.read(buffer)) >= 0) {
out.write(buffer, 0, n);
}
// 使用指定的 charsetName,通過解碼字節(jié)將緩沖區(qū)內(nèi)容轉(zhuǎn)換為字符串
return out.toString("utf-8");
}
public static void main(String[] args) throws IOException {
String str="看甲方時點(diǎn)擊翻身肯
"; //內(nèi)容大小控制在240byte, >240 進(jìn)行壓縮·否則不壓··
System.out.println("原文大小:"+str.getBytes().length+"
壓縮前:"+str);
String compress = GZIP.compress(str);
System.out.println("解壓大小:"+compress.getBytes().length+"
壓縮后:"+compress);
String uncompress = GZIP.unCompress(compress);
System.out.println("解壓大小:"+uncompress.getBytes().length+"
解壓縮:"+uncompress);
}
}
總結(jié)
以上是生活随笔為你收集整理的Android GZIP压缩与解压的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 中行学生卡怎么注销?这几个事项要注意!
- 下一篇: Mac 下 Android Studio