最近对接了某银行的账单下载,账单接口采用了java开发并且,进行了deflate压缩.
使用Delphi解压缩的时候,Delphi XE版本目前支持直接的deflate解压缩:
查了一下官方文档
Description
This example shows the usage of TZCompressionStream and TZDecompressionStream. Supply the two filenames in the Edit controls of the main form and then press either the Compress or the Decompress button to do the actions. When the Compress button is pressed, the '.zip' extension is automatically added to the output file. When the Decompress button is pressed, '.zip' is automatically removed.
Code
procedure TForm1.btnCompressClick(Sender: TObject);
var
LInput, LOutput: TFileStream;
LZip: TZCompressionStream;
begin
{ Create the Input, Output, and Compressed streams. }
LInput := TFileStream.Create(Edit1.Text, fmOpenRead);
LOutput := TFileStream.Create(Edit2.Text + '.zip', fmCreate);
LZip := TZCompressionStream.Create(clDefault, LOutput);
{ Compress data. }
LZip.CopyFrom(LInput, LInput.Size);
{ Free the streams. }
LZip.Free;
LInput.Free;
LOutput.Free;
end;
procedure TForm1.btnDecompressClick(Sender: TObject);
var
LInput, LOutput: TFileStream;
LUnZip: TZDecompressionStream;
begin
{ Create the Input, Output, and Decompressed streams. }
LInput := TFileStream.Create(Edit1.Text, fmOpenRead);
LOutput := TFileStream.Create(ChangeFileExt(Edit1.Text, 'txt'), fmCreate);
LUnZip := TZDecompressionStream.Create(LInput);
{ Decompress data. }
LOutput.CopyFrom(LUnZip, 0);
{ Free the streams. }
LUnZip.Free;
LInput.Free;
LOutput.Free;
end;
自己稍作改造就能对string也进行deflate压缩及解压缩了
function DEZIP(INSTR: string): string;
var
LOutput: TFileStream;
LUnZip: TZDecompressionStream;
Buf,BufBack: TBytes;
strMem,astream:TMemoryStream ;
begin
try
Result := '';
strMem := TMemoryStream.Create;
astream := TMemoryStream.Create;
Buf := TNetEncoding.Base64.DecodeStringToBytes(INSTR);
astream.Position := 0;
astream.Write(Buf,Length(buf));
astream.Position := 0;
{ Create the Input, Output, and Decompressed streams. }
LOutput := TFileStream.Create('zhangdan.txt', fmCreate);
LUnZip := TZDecompressionStream.Create(astream);
{ Decompress data. }
LOutput.CopyFrom(LUnZip, 0);
strMem.CopyFrom(LUnZip,0);
SetLength(BufBack,strMem.Size);
strMem.Position := 0;
strMem.ReadData(BufBack,Length(BufBack));
Result := TEncoding.UTF8.GetString(BufBack);
finally
{ Free the streams. }
LUnZip.Free;
FreeAndNil( strMem );
FreeAndNil( astream );
LOutput.Free;
end;
end;