Java

Java中如何利用zlib进行数据压缩

小樊
87
2024-08-11 02:07:38
栏目: 编程语言

在Java中可以使用java.util.zip包中的Deflater类和Inflater类来进行数据压缩和解压缩。以下是一个简单的示例代码:

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

public class ZlibExample {

    public static void main(String[] args) {
        String data = "Hello, world!";
        byte[] compressedData = compress(data.getBytes());
        byte[] decompressedData = decompress(compressedData);

        System.out.println("Original data: " + data);
        System.out.println("Compressed data: " + new String(compressedData));
        System.out.println("Decompressed data: " + new String(decompressedData));
    }

    public static byte[] compress(byte[] data) {
        Deflater deflater = new Deflater();
        deflater.setInput(data);
        deflater.finish();

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length);
        byte[] buffer = new byte[1024];
        while (!deflater.finished()) {
            int count = deflater.deflate(buffer);
            outputStream.write(buffer, 0, count);
        }

        deflater.end();
        return outputStream.toByteArray();
    }

    public static byte[] decompress(byte[] data) {
        Inflater inflater = new Inflater();
        inflater.setInput(data);

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length);
        byte[] buffer = new byte[1024];
        while (!inflater.finished()) {
            try {
                int count = inflater.inflate(buffer);
                outputStream.write(buffer, 0, count);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        inflater.end();
        return outputStream.toByteArray();
    }
}

在上面的示例中,compress方法用于压缩数据,decompress方法用于解压缩数据。可以通过调用这两个方法来对数据进行压缩和解压缩操作。

0
看了该问题的人还看了