溫馨提示×

如何用Java實現(xiàn)zlib壓縮和解壓

小樊
95
2024-08-11 02:05:40
欄目: 編程語言

可以使用Java中提供的InflaterDeflater類來實現(xiàn)zlib壓縮和解壓功能。

以下是一個簡單的示例代碼,演示如何使用Java實現(xiàn)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()方法用于對數(shù)據(jù)進行壓縮,decompress()方法用于對壓縮后的數(shù)據(jù)進行解壓。在main()方法中,我們演示了如何壓縮和解壓數(shù)據(jù)。

0