1. 程式人生 > >GZIP壓縮與解壓

GZIP壓縮與解壓

public class GZIP {
    /**
     * 字串的壓縮
     * 
     * @param str
     *            待壓縮的字串
     * @return 返回壓縮後的字串
     * @throws IOException
     */
    public static String compress(String str) throws IOException {
        if (null == str || str.length() <= 0) {
            return str;
        }
        
// 建立一個新的輸出流 ByteArrayOutputStream out = new ByteArrayOutputStream(); // 使用預設緩衝區大小建立新的輸出流 GZIPOutputStream gzip = new GZIPOutputStream(out); // 將位元組寫入此輸出流 gzip.write(str.getBytes("utf-8")); // 因為後臺預設字符集有可能是GBK字符集,所以此處需指定一個字符集 gzip.close(); // 使用指定的 charsetName,通過解碼位元組將緩衝區內容轉換為字串
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; } // 建立一個新的輸出流 ByteArrayOutputStream out = new ByteArrayOutputStream(); // 建立一個 ByteArrayInputStream,使用 buf 作為其緩衝區陣列 ByteArrayInputStream in = new ByteArrayInputStream(str.getBytes("ISO-8859-1")); // 使用預設緩衝區大小建立新的輸入流 GZIPInputStream gzip = new GZIPInputStream(in); byte[] buffer = new byte[256]; int n = 0; // 將未壓縮資料讀入位元組陣列 while ((n = gzip.read(buffer)) >= 0) { out.write(buffer, 0, n); } // 使用指定的 charsetName,通過解碼位元組將緩衝區內容轉換為字串 return out.toString("utf-8"); } public static void main(String[] args) throws IOException { String str="看甲方時點選翻身肯\n"; //內容大小控制在240byte, >240 進行壓縮·否則不壓·· System.out.println("原文大小:"+str.getBytes().length+" \n壓縮前:"+str); String compress = GZIP.compress(str); System.out.println("解壓大小:"+compress.getBytes().length+" \n壓縮後:"+compress); String uncompress = GZIP.unCompress(compress); System.out.println("解壓大小:"+uncompress.getBytes().length+" \n解壓縮:"+uncompress); } }