unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
Button3: TButton;
Button4: TButton;
Memo1: TMemo;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure Button4Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
//添加一個 Memo1 然後修改其內容
procedure TForm1.Button1Click(Sender: TObject);
begin
WriteComponentResFile('c:\temp\memo.dat', Memo1);
{只此一句就可以把當前的 Memo 的狀態序列化到文件}
end;
//反序列化, 讀回
procedure TForm1.Button2Click(Sender: TObject);
begin
ReadComponentResFile('c:\temp\memo.dat', Memo1);
{一句話就可以讀回, 不管是經過了什麼操作(甚至是關機)}
end;
{
這好像和流沒什麼關系, 其實這就是流的典型操作,
WriteComponentResFile 和 ReadComponentResFile 分別調用了流類的
WriteComponentRes 與 ReadComponentRes 方法.
下面用更直接的流的方式重新實現一次:
}
//序列化
procedure TForm1.Button3Click(Sender: TObject);
var
stream: TStream;
const
strPath = 'c:\temp\m.dat';
begin
stream := TFileStream.Create(strPath, fmCreate);
stream.WriteComponentRes(Memo1.ClassName, Memo1);
{WriteComponentRes 有兩個參數: 文件名和組件名}
stream.Free;
end;
//反序列化
procedure TForm1.Button4Click(Sender: TObject);
var
stream: TStream;
const
strPath = 'c:\temp\m.dat';
begin
stream := TFileStream.Create(strPath, fmOpenRead);
stream.ReadComponentRes(Memo1);
{ReadComponentRes 只有一個參數: 組件名}
stream.Free;
end;
end.