温馨提示×

如何用Java实现zlib压缩和解压

小樊
95
2024-08-11 02:05:40
栏目: 编程语言

可以使用Java中提供的InflaterDeflater类来实现zlib压缩和解压功能。

以下是一个简单的示例代码,演示如何使用Java实现zlib压缩和解压:

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

public class ZlibExample {
  
  public static byte[] compress(byte[] data) {
    Deflater deflater = new Deflater();
    deflater.setInput(data);
    deflater.finish();
    
    byte[] buffer = new byte[data.length];
    int compressedDataLength = deflater.deflate(buffer);
    
    byte[] compressedData = new byte[compressedDataLength];
    System.arraycopy(buffer, 0, compressedData, 0, compressedDataLength);
    
    deflater.end();
    
    return compressedData;
  }
  
  public static byte[] decompress(byte[] compressedData) {
    Inflater inflater = new Inflater();
    inflater.setInput(compressedData);
    
    byte[] buffer = new byte[compressedData.length * 2];
    int decompressedDataLength;
    try {
      decompressedDataLength = inflater.inflate(buffer);
    } catch (Exception e) {
      decompressedDataLength = 0;
    }
    
    byte[] decompressedData = new byte[decompressedDataLength];
    System.arraycopy(buffer, 0, decompressedData, 0, decompressedDataLength);
    
    inflater.end();
    
    return decompressedData;
  }
  
  public static void main(String[] args) {
    String data = "Hello, World!";
    byte[] compressedData = compress(data.getBytes());
    System.out.println("Compressed data: " + new String(compressedData));
    
    byte[] decompressedData = decompress(compressedData);
    System.out.println("Decompressed data: " + new String(decompressedData));
  }
}

在上面的示例中,compress()方法用于对数据进行压缩,decompress()方法用于对压缩后的数据进行解压。在main()方法中,我们演示了如何压缩和解压数据。

0