Java

java压缩字符串的方法是什么

小亿
88
2024-03-30 16:27:58
栏目: 编程语言

在Java中,可以使用java.util.zip包中的DeflaterInflater类来进行字符串的压缩和解压缩操作。以下是一个简单的示例代码:

import java.util.zip.Deflater;
import java.util.zip.Inflater;

public class Main {
    public static byte[] compressString(String input) {
        try {
            byte[] inputBytes = input.getBytes();
            Deflater deflater = new Deflater();
            deflater.setInput(inputBytes);
            deflater.finish();
            byte[] outputBytes = new byte[inputBytes.length];
            int compressedSize = deflater.deflate(outputBytes);
            byte[] compressedBytes = new byte[compressedSize];
            System.arraycopy(outputBytes, 0, compressedBytes, 0, compressedSize);
            return compressedBytes;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String decompressString(byte[] input) {
        try {
            Inflater inflater = new Inflater();
            inflater.setInput(input);
            byte[] outputBytes = new byte[input.length];
            int decompressedSize = inflater.inflate(outputBytes);
            byte[] decompressedBytes = new byte[decompressedSize];
            System.arraycopy(outputBytes, 0, decompressedBytes, 0, decompressedSize);
            return new String(decompressedBytes);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) {
        String input = "Hello, this is a test string for compression.";
        byte[] compressedData = compressString(input);
        String decompressedData = decompressString(compressedData);
        System.out.println("Original data: " + input);
        System.out.println("Compressed data: " + new String(compressedData));
        System.out.println("Decompressed data: " + decompressedData);
    }
}

在上面的示例中,compressString方法用于压缩输入的字符串,而decompressString方法用于解压缩输入的字节数组。通过这两个方法,可以实现字符串的压缩和解压缩操作。

0
看了该问题的人还看了