温馨提示×

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

小樊
87
2024-08-11 02:16:37
栏目: 编程语言

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

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

public class ZlibDecompress {

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

            ByteArrayOutputStream outputStream = new ByteArrayOutputStream(compressedData.length);
            byte[] buffer = new byte[1024];

            while (!inflater.finished()) {
                int count = inflater.inflate(buffer);
                outputStream.write(buffer, 0, count);
            }

            byte[] decompressedData = outputStream.toByteArray();
            outputStream.close();

            return decompressedData;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) {
        byte[] compressedData = ...; // 传入压缩过的数据
        byte[] decompressedData = decompress(compressedData);

        System.out.println("解压后的数据:" + new String(decompressedData));
    }
}

在上面的示例中,decompress方法接收一个压缩过的数据字节数组,并返回解压后的数据字节数组。在main方法中,我们可以传入压缩过的数据,并打印出解压后的数据。

0