91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

如何用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
忻州市| 靖西县| 乾安县| 梅河口市| 祁东县| 万载县| 武城县| 沈阳市| 定边县| 屯留县| 长顺县| 鸡泽县| 琼海市| 故城县| 阆中市| 兰坪| 青冈县| 垦利县| 赤壁市| 乐昌市| 海南省| 浦县| 聂荣县| 九龙坡区| 金阳县| 小金县| 垣曲县| 巍山| 西安市| 宁南县| 阳谷县| 武义县| 辽阳市| 会宁县| 三江| 崇州市| 西乌| 宝丰县| 大理市| 南安市| 墨脱县|