新闻资讯

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻资讯列表

java压缩字符串的有哪些方法,java压缩字符串 压缩率最高

发布时间:2024-03-30 16:27:58

java紧缩字符串的有哪些方法

在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方法用于解紧缩输入的字节数组。通过这两个方法,可以实现字符串的紧缩和解紧缩操作。