對數據進行GZIP壓縮或解壓縮


/**
     * 對data進行GZIP解壓縮
     * @param data
     * @return
     * @throws Exception 
     */
    public static String unCompress(byte[] data) throws Exception {
        if (null == data && data.length <= 0) {
            return null;
        }
        String reString = "";
        try {
            //創建一個新的byte數組輸出流
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            //創建一個byte數組輸入流
            ByteArrayInputStream in = new ByteArrayInputStream(data);
            //創建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,通過解碼字節將緩沖區內容轉換為字符串
            reString = out.toString("UTF-8");
            out.close();
            in.close();
            gzip.close();
        } catch (Exception e) {
            // TODO 自動生成的 catch 塊
            e.printStackTrace();
        }
        return reString;
    }
    
    /**
     * 對字符串進行gzip壓縮
     * @param data
     * @return
     * @throws IOException 
     */
    public static String compress(String data) throws Exception {
        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");
    }

 


免責聲明!

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



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