字符串壓縮方式解決varchar超過4000的問題

/**
 * @author pengchao
 * @version 2020.04.15
 */
public class StrZipUtils {

    /**
     * 字符串壓縮
     * @param str   待壓縮的數據信息
     * @return
     * @throws IOException
     */
    public String doTestZip(String str) throws IOException {
        if (null == str || str.length() <= 0) {
            return str;
        }
        // 創建一個新的 byte 數組輸出流
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        // 使用默認緩衝區大小創建新的輸出流
        GZIPOutputStream gzip = new GZIPOutputStream(out);
        // 將 b.length 個字節寫入此輸出流
        gzip.write(str.getBytes());
        gzip.close();
        // 使用指定的 charsetName,通過解碼字節將緩衝區內容轉換爲字符串
        out.toString("ISO-8859-1");
        return out.toString("ISO-8859-1");
    }

    /**
     * 解壓縮
     * @param str   待解壓縮的數據
     * @return  解壓縮後的
     * @throws IOException
     */
    public static String doTestUnZip(String str) throws IOException {
        if (null == str || str.length() <= 0) {
            return str;
        }
        // 創建一個新的 byte 數組輸出流
        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) {// 將未壓縮數據讀入字節數組
            // 將指定 byte 數組中從偏移量 off 開始的 len 個字節寫入此 byte數組輸出流
            out.write(buffer, 0, n);
        }
        // 使用指定的 charsetName,通過解碼字節將緩衝區內容轉換爲字符串
        return out.toString("UTF-8");
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章