Java中使用zlib压缩数据的方法

   2024-10-01 9320
核心提示:在Java中使用zlib压缩数据可以通过Java标准库中的Deflater和Inflater类来实现。以下是一个示例代码:import java.util.zip.Defla

在Java中使用zlib压缩数据可以通过Java标准库中的Deflater和Inflater类来实现。以下是一个示例代码:

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);    }}

在上面的示例中,我们定义了compressData和decompressData方法来分别压缩和解压数据。在main方法中,我们先将字符串"Hello, world!"转换为字节数组,然后进行压缩和解压操作,最后打印解压后的字符串。

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式 | 网站留言    |  赣ICP备2021007278号