杰瑞科技汇

Java字符串如何用GZIP压缩?

Java GZIP 字符串压缩

在 Java 中,可以使用 java.util.zip 包中的类来对字符串进行 GZIP 压缩,以下是完整的实现方法:

Java字符串如何用GZIP压缩?-图1
(图片来源网络,侵删)

基本压缩方法

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;
import java.nio.charset.StandardCharsets;
public class GzipCompressor {
    /**
     * 将字符串压缩为GZIP字节数组
     * @param str 要压缩的字符串
     * @return 压缩后的字节数组
     * @throws IOException 如果压缩过程中发生错误
     */
    public static byte[] compress(String str) throws IOException {
        if (str == null || str.isEmpty()) {
            return new byte[0];
        }
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try (GZIPOutputStream gzipOutputStream = new GZIPOutputStream(byteArrayOutputStream)) {
            gzipOutputStream.write(str.getBytes(StandardCharsets.UTF_8));
        }
        return byteArrayOutputStream.toByteArray();
    }
    /**
     * 将GZIP字节数组解压缩为字符串
     * @param compressed 压缩的字节数组
     * @return 解压后的字符串
     * @throws IOException 如果解压过程中发生错误
     */
    public static String decompress(byte[] compressed) throws IOException {
        if (compressed == null || compressed.length == 0) {
            return "";
        }
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try (java.util.zip.GZIPInputStream gzipInputStream = 
                new java.util.zip.GZIPInputStream(new java.io.ByteArrayInputStream(compressed))) {
            byte[] buffer = new byte[1024];
            int len;
            while ((len = gzipInputStream.read(buffer)) > 0) {
                byteArrayOutputStream.write(buffer, 0, len);
            }
        }
        return byteArrayOutputStream.toString(StandardCharsets.UTF_8.name());
    }
}

使用示例

public class Main {
    public static void main(String[] args) {
        String originalString = "这是一个需要压缩的测试字符串,它可能包含很多重复的内容。";
        try {
            // 压缩字符串
            byte[] compressed = GzipCompressor.compress(originalString);
            System.out.println("压缩后大小: " + compressed.length + " 字节");
            // 解压字符串
            String decompressed = GzipCompressor.decompress(compressed);
            System.out.println("解压后字符串: " + decompressed);
            // 验证解压后的字符串是否与原始字符串一致
            System.out.println("验证结果: " + originalString.equals(decompressed));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

高级用法(带Base64编码)

如果需要将压缩后的字节数组转换为字符串形式(如存储在文本字段中),可以使用Base64编码:

import java.util.Base64;
public class GzipWithBase64 {
    public static String compressAndEncode(String str) throws IOException {
        byte[] compressed = GzipCompressor.compress(str);
        return Base64.getEncoder().encodeToString(compressed);
    }
    public static String decodeAndDecompress(String encoded) throws IOException {
        byte[] compressed = Base64.getDecoder().decode(encoded);
        return GzipCompressor.decompress(compressed);
    }
}

注意事项

  1. 字符编码:始终使用 StandardCharsets.UTF_8 或其他明确的字符集,避免平台默认字符集的问题
  2. 异常处理:压缩和解压操作可能抛出 IOException,需要适当处理
  3. 空值检查:处理输入字符串为 null 或空的情况
  4. 性能考虑:对于非常大的字符串,可能需要考虑流式处理或分块处理
  5. 压缩效果:GZIP 对重复文本效果更好,对于已经压缩过的数据(如JPEG)效果不明显

代码提供了完整的 GZIP 字符串压缩和解压功能,可以根据实际需求进行调整。

Java字符串如何用GZIP压缩?-图2
(图片来源网络,侵删)
分享:
扫描分享到社交APP
上一篇
下一篇