技术交流28群

服务热线

135-6963-3175

微信服务号

GZIP压缩字符串,JSON压缩 更新时间 2023-9-30 浏览2493次

下面是使用Java实现对字符串进行GZIP压缩的示例代码:

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import java.nio.charset.StandardCharsets;
public class GzipCompressionExample {
    public static byte[] compress(String input) throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try (GZIPOutputStream gzipOutputStream = new GZIPOutputStream(outputStream)) {
            gzipOutputStream.write(input.getBytes(StandardCharsets.UTF_8));
        }
        return outputStream.toByteArray();
    }
    public static String decompress(byte[] compressedData) throws IOException {
        ByteArrayInputStream inputStream = new ByteArrayInputStream(compressedData);
        try (GZIPInputStream gzipInputStream = new GZIPInputStream(inputStream)) {
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = gzipInputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            return outputStream.toString(StandardCharsets.UTF_8);
        }
    }
    public static void main(String[] args) {
        String input = "Hello, world!";
        try {
            byte[] compressedData = compress(input);
            String decompressedOutput = decompress(compressedData);
            System.out.println("Original: " + input);
            System.out.println("Compressed: " + new String(compressedData, StandardCharsets.UTF_8));
            System.out.println("Decompressed: " + decompressedOutput);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}



在上述示例中,compress() 方法接受一个字符串作为输入,并返回压缩后的字节数组。decompress() 方法接受一个压缩后的字节数组,并返回解压缩后的字符串。

在 main() 方法中,我们使用示例字符串 "Hello, world!" 进行压缩和解压缩操作,并打印原始字符串、压缩后的字节数组和解压缩后的字符串。

请注意,GZIP压缩是一种无损压缩算法,可以有效地压缩数据,但会增加一些额外的计算开销。在实际使用时,请根据你的需求和数据量进行评估。