Delphi docking java deflate compression and decompression

Recently, I downloaded a bill from a bank. The bill interface was developed in java and compressed with deflate.

When using Delphi to decompress, the Delphi XE version currently supports direct deflate decompression:

Check the official document

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;

You can also perform deflate compression and decompression on the string with a little modification.


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;

Guess you like

Origin blog.csdn.net/fyq158797/article/details/131554916