溫馨提示×

Java中如何利用zlib進(jìn)行數(shù)據(jù)壓縮

小樊
87
2024-08-11 02:07:38
欄目: 編程語言

在Java中可以使用java.util.zip包中的Deflater類和Inflater類來進(jìn)行數(shù)據(jù)壓縮和解壓縮。以下是一個簡單的示例代碼:

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方法用于壓縮數(shù)據(jù),decompress方法用于解壓縮數(shù)據(jù)??梢酝ㄟ^調(diào)用這兩個方法來對數(shù)據(jù)進(jìn)行壓縮和解壓縮操作。

0