public class GzipUtils { /** * 對字符串進行gzip壓縮 * @param data * @return * @throws IOException */ public static String compress(String data) throws IOException { if (null == data || data.length() <= 0) { return data; } //創建一個新的byte數組輸出流 ByteArrayOutputStream out = new ByteArrayOutputStream(); //使用默認緩沖區大小創建新的輸出流 GZIPOutputStream gzip = new GZIPOutputStream(out); //將b.length個字節寫入此輸出流 gzip.write(data.getBytes()); gzip.flush(); gzip.close(); //使用指定的charsetName,通過解碼字節將緩沖區內容轉換為字符串 return out.toString("ISO-8859-1"); } /** * 對字符串進行解壓縮 * @param data * @return * @throws Exception */ public static String unCompress(String data) throws Exception { if (null == data && data.length() <= 0) { return data; } //創建一個新的byte數組輸出流 ByteArrayOutputStream out = new ByteArrayOutputStream(); //創建一個byte數組輸入流 ByteArrayInputStream in = new ByteArrayInputStream(data.getBytes("ISO-8859-1")); //創建gzip輸入流 GZIPInputStream gzip = new GZIPInputStream(in); byte[] buf = new byte[1024]; int len = 0; while ((len = gzip.read(buf)) >= 0) { out.write(buf, 0, len); } // 使用指定的 charsetName,通過解碼字節將緩沖區內容轉換為字符串 return out.toString("UTF-8"); }
Gzip壓縮和解壓數據代碼