首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 與 Delphi 跨平台 Zlib 壓縮互通實作指南

     編輯:Java 相關知識

架構場景

Delphi 客戶端 ↔ J2EE 伺服器端,XML 資料交換,引入 Zlib 壓縮降低頻寬,雙端需互通解壓。

Java 端實作 (JDK 內建 java.util.zip)

public class ZlibUtils {
    // 解壓:Base64 解碼 → InflaterOutputStream → 字串
    public static String decompress(String base64Data) {
        try {
            byte[] decoded = Base64.getDecoder().decode(base64Data);
            try (ByteArrayInputStream bis = new ByteArrayInputStream(decoded);
                 InflaterInputStream iis = new InflaterInputStream(bis);
                 ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
                byte[] buf = new byte[1024];
                int len;
                while ((len = iis.read(buf)) != -1) bos.write(buf, 0, len);
                return bos.toString(StandardCharsets.UTF_8);
            }
        } catch (Exception e) { throw new RuntimeException("UNZIP_ERR", e); }
    }

    // 壓縮:字串 → DeflaterOutputStream → Base64 編碼
    public static String compress(String data) {
        try {
            try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
                 DeflaterOutputStream dos = new DeflaterOutputStream(bos)) {
                dos.write(data.getBytes(StandardCharsets.UTF_8));
                dos.finish();
                return Base64.getEncoder().encodeToString(bos.toByteArray());
            }
        } catch (Exception e) { throw new RuntimeException("ZIP_ERR", e); }
    }
}

Delphi 端實作 (VCLZIP + Base64 → DLL 匯出)

function Cmip_CompressStr(txt: PChar): PChar; stdcall;
var
  zip: TVclZip;
  compressed: string;
begin
  zip := TVclZip.Create(nil);
  try
    compressed := zip.ZLibCompressString(txt);
    Result := StrNew(PChar(Base64EncodeStr(compressed)));
  finally
    zip.Free;
  end;
end;

function Cmip_DeCompressStr(txt: PChar): PChar; stdcall;
var
  unzip: TVCLUnZip;
  decompressed: string;
begin
  unzip := TVCLUnZip.Create(nil);
  try
    decompressed := unzip.ZLibDecompressString(Base64DecodeStr(txt));
    Result := StrNew(PChar(decompressed));
  finally
    unzip.Free;
  end;
end;

互通關鍵點

  • 壓縮演算法一致:雙端均使用標準 Zlib (RFC 1950/1951)。
  • Base64 編碼:二進位壓縮資料安全傳輸於 XML/JSON/HTTP。
  • 字元編碼約定:雙端統一 UTF-8,避免中文亂碼。
  • 記憶體管理:Delphi DLL 匯出字串需明確所有權(StrNew/呼叫端釋放)。

現代化替代

Java 端可升級 java.util.Base64 (Java 8+);Delphi 可用 System.ZLib (XE2+) 移除第三方依賴;跨語言序列化建議改用 Protobuf/Avro + gzip,效能與演進性更優。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved