亚洲激情专区-91九色丨porny丨老师-久久久久久久女国产乱让韩-国产精品午夜小视频观看

溫馨提示×

如何用Java實現zlib壓縮和解壓

小樊
82
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
高要市| 凌源市| 淳安县| 临漳县| 九龙城区| 东台市| 枣阳市| 理塘县| 当阳市| 江陵县| 元氏县| 龙山县| 绥芬河市| 高陵县| 广德县| 克拉玛依市| 哈密市| 罗源县| 虞城县| 马尔康县| 嘉义市| 繁峙县| 临泉县| 南丰县| 都江堰市| 靖远县| 密山市| 富锦市| 东海县| 邢台市| 油尖旺区| 会泽县| 耒阳市| 芜湖县| 东港市| 枝江市| 密云县| 延安市| 高密市| 佳木斯市| 安多县|