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

avatar
作者
猴君
阅读量:0

在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!"转换为字节数组,然后进行压缩和解压操作,最后打印解压后的字符串。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!