GZIP壓縮、解壓縮工具類

GZIP壓縮、解壓縮工具類:數組

public class GZIPUtiles {
    
    
    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");
    }
    
    
    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,經過解碼字節將緩衝區內容轉換爲字符串 
         //String string = out.toString("utf-8");
         //String unescapeJava = StringEscapeUtils.unescapeJava(string);
         return out.toString("utf-8"); 
         }


}
相關文章
相關標籤/搜索