使用gzip对字符串进行压缩处理by Java

/ 后端 / 没有评论 / 420浏览

需要注意的是,仅对字符串长度较大时有作用,字符串较短时由于base64编码的缘故可能会大于原有字符串长度~

 public static String gzip(String string) {
        String result = null;
        if (StringUtils.isBlank(string)) {
            return result;
        }
        ByteArrayOutputStream out = null;
        GZIPOutputStream gzip = null;
        try {
            out = new ByteArrayOutputStream();
            gzip = new GZIPOutputStream(out);
            gzip.write(string.getBytes(StandardCharsets.UTF_8));
            result = Base64.encode(out.toByteArray());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (gzip != null) {
                    gzip.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    public static String unGzip(String string) {
        String result = null;
        if (StringUtils.isBlank(string)) {
            return result;
        }
        ByteArrayOutputStream out = null;
        ByteArrayInputStream in = null;
        GZIPInputStream ungzip = null;
        byte[] bytes = Base64.decode(string);
        try {
            out = new ByteArrayOutputStream();
            in = new ByteArrayInputStream(bytes);
            ungzip = new GZIPInputStream(in);
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = ungzip.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            result = out.toString(StandardCharsets.UTF_8.toString());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (ungzip != null) {
                    ungzip.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }