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

 


免責聲明!

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



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