When I was in my college I work as part time programmer in a software house. I got a task to create a software updater. The software updater work by copying new files to the already installed application in the client's computers. To make update file easier to distribute I need to compress the new files and combine them into a file.
In Delphi or Lazarus we can use TFileStream class to access files and using TCompressionStream in the zstream unit to compress data from memory buffer to output stream that can be any TStream object including TFileStream or TMemoryStream. To decompress later you can use TDecompressionStream class.
If ZLib compression is not enough you can use BZip2 library for stronger compression.
Bellow is an example of using ZLib TCompressionStream and TDecompressionStream class:
- program TestCompressAndDecompress;
- {$MODE DELPHI}
- uses SysUtils, Classes, zstream;
- var
- F: TMemoryStream;
- Comp: TCompressionStream;
- Decomp: TDecompressionStream;
- X, Y: AnsiString;
- begin
- F := TMemoryStream.Create;
- try
- Comp := TCompressionStream.Create(clMax, F);
- try
- X := 'Compress and Decompress array of bytes or a file using ZLib in Delphi or Free Pascal Lazarus';
- Comp.Write(X[1], Length(X));
- finally
- Comp.Free;
- end;
- WriteLn('Original Text: "',X,'"');
- WriteLn('Original Size: ',Length(X),' bytes.');
- WriteLn('Compressed Size: ',F.Size,' bytes.');
- F.Position := 0;
- Decomp := TDecompressionStream.Create(F);
- try
- SetLength(Y, Length(X));
- Decomp.Read(Y[1], Length(Y));
- finally
- Decomp.Free;
- end;
- WriteLn('Decompressed Text: "',Y,'"');
- finally
- F.Free;
- end;
- end.
Tidak ada komentar:
Posting Komentar