Skip to content

字符串工具

压缩与解压缩

字符串的压缩与解压缩主要用于减少网络传输的数据量。

压缩字符串

java
/**
 * 压缩字符串
 * @param str 带压缩字符串
 * @return
 */
public static String compress(String str) {
    if (str == null || str.length() == 0) {
        return str;
    }
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    GZIPOutputStream gzip = null;
    try {
        gzip = new GZIPOutputStream(out);
        gzip.write(str.getBytes());
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (gzip != null) {
            try {
                gzip.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return new Base64().encodeToString(out.toByteArray());
}

解压缩字符串

java
/**
 * 使用gzip解压缩
 * @param compressedStr 压缩字符串
 * @return
 */
public static String uncompress(String compressedStr) {
    if (compressedStr == null) {
        return null;
    }
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ByteArrayInputStream in = null;
    GZIPInputStream ginzip = null;
    byte[] compressed = null;
    String decompressed = null;
    try {
        compressed = Base64.decodeBase64(compressedStr);
        in = new ByteArrayInputStream(compressed);
        ginzip = new GZIPInputStream(in);
        byte[] buffer = new byte[1024];
        int offset = -1;
        while ((offset = ginzip.read(buffer)) != -1) {
            out.write(buffer, 0, offset);
        }
        decompressed = out.toString();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (ginzip != null) {
            try {
                ginzip.close();
            } catch (IOException ignored) {
            }
        }
        if (in != null) {
            try {
                in.close();
            } catch (IOException ignored) {
            }
        }
        try {
            out.close();
        } catch (IOException ignored) {
        }
    }
    return decompressed;
}