服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

zlib压缩算法在java与delphi间交互实现

一个典型应用中,使用delphi作为客户端,j2ee服务端,两者之间用xml作为数据交换,为了提高效率,对xml数据进行压缩,为此需要找到一种压缩/解压算法能够两个平台之间交互处理,使用zlib算法就是一个不错的解决方案。

1、java实现

在jdk中,在java.util.zip包中已经内置了zlib的实现,示例代码如下:

1//解压
2 public string decompressdata(string encdata) {
3 try {
4 bytearrayoutputstream bos = new bytearrayoutputstream(); 
5 inflateroutputstream zos = new inflateroutputstream(bos); 
6 zos.write(convertfrombase64(encdata)); 
7 zos.close(); 
8 return new string(bos.tobytearray()); 
9 } catch (exception ex) {
10 ex.printstacktrace(); 
11 return "unzip_err"; 
12 }
13 }
14
15 //压缩
16 public string compressdata(string data) {
17 try {
18 bytearrayoutputstream bos = new bytearrayoutputstream(); 
19 deflateroutputstream zos = new deflateroutputstream(bos); 
20 zos.write(data.getbytes()); 
21 zos.close(); 
22 return new string(converttobase64(bos.tobytearray())); 
23 } catch (exception ex) {
24 ex.printstacktrace(); 
25 return "zip_err"; 
26 }
27 }

2、delphi中的实现

在delphi中,有第3方的控件可以利用来实现压缩/解压,这里我们选择vclzip v3.04,可以从这里下载http://www.vclzip.net。为了提高通用性,我们可以编写一个标准的dll,就可以在win32平台随意调用了,关键代码如下:

function cmip_compressstr(txt: pchar): pchar; stdcall; 
var
zip: tvclzip; 
compr: string; 
data: pchar; 
begin
zip := tvclzip.create(nil); 
compr := zip.zlibcompressstring(txt); 
data := pchar(base64encodestr(compr)); 
result := strnew(data); 
zip.free
end; 

function cmip_decompressstr(txt: pchar): pchar; stdcall; 
var
zip: tvclunzip; 
compr: string; 
data: pchar; 
begin
zip := tvclunzip.create(nil); 
compr := zip.zlibdecompressstring(base64decodestr(txt)); 
data := strnew(pchar(compr)); 
result := data; 
zip.free
end;

扫描关注微信公众号