按下“写入”按钮时,在TEdit中输入的字符串将压缩为UTF-8字节字符串并保存。
uses System.IOUtils, System.ZLib;
procedure TForm1.Button1Click(Sender: TObject);
var
FN: string;
Bytes: TBytes;
FS: TFileStream;
CS: TZCompressionStream;
begin
FN := System.IOUtils.TPath.Combine(System.IOUtils.TPath.GetDocumentsPath(),
'test.gz');
FS := TFileStream.Create(FN, fmCreate);
CS := TZCompressionStream.Create(FS);
Bytes := TEncoding.UTF8.GetBytes(Edit1.Text);
CS.Write(Bytes, Length(Bytes));
Bytes := TEncoding.UTF8.GetBytes(Edit2.Text);
CS.Write(Bytes, Length(Bytes));
CS.Free;
FS.Free;
end;
按下“读取”按钮时,将读取并恢复压缩和保存的数据。
procedure TForm1.Button2Click(Sender: TObject);
var
FN: string;
DS: TZDecompressionStream;
FS: TFileStream;
Bytes: TBytes;
begin
FN := System.IOUtils.TPath.Combine(System.IOUtils.TPath.GetDocumentsPath(), 'test.gz');
FS := TFileStream.Create(FN, fmOpenRead);
DS := TZDecompressionStream.Create(FS);
SetLength(Bytes, DS.Size);
DS.Position := 0;
DS.Read(Bytes, DS.Size);
DS.Free;
FS.Free;
Label1.Text := TEncoding.UTF8.GetString(Bytes);
end;