溫馨提示×

Java中使用zlib壓縮數據的方法

小樊
105
2024-08-11 02:03:39
欄目: 編程語言

在Java中使用zlib壓縮數據可以通過Java標準庫中的DeflaterInflater類來實現。以下是一個示例代碼:

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

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

        byte[] buffer = new byte[1024];
        int compressedDataLength = deflater.deflate(buffer);

        byte[] compressedData = new byte[compressedDataLength];
        System.arraycopy(buffer, 0, compressedData, 0, compressedDataLength);

        deflater.end();

        return compressedData;
    }

    public static byte[] decompressData(byte[] compressedData) {
        Inflater inflater = new Inflater();
        inflater.setInput(compressedData);

        byte[] buffer = new byte[1024];
        int decompressedDataLength = inflater.inflate(buffer);

        byte[] decompressedData = new byte[decompressedDataLength];
        System.arraycopy(buffer, 0, decompressedData, 0, decompressedDataLength);

        inflater.end();

        return decompressedData;
    }

    public static void main(String[] args) {
        String input = "Hello, world!";
        byte[] inputData = input.getBytes();

        byte[] compressedData = compressData(inputData);
        byte[] decompressedData = decompressData(compressedData);

        String output = new String(decompressedData);
        System.out.println(output);
    }
}

在上面的示例中,我們定義了compressDatadecompressData方法來分別壓縮和解壓數據。在main方法中,我們先將字符串"Hello, world!"轉換為字節數組,然后進行壓縮和解壓操作,最后打印解壓后的字符串。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女