// 寫入中文
procedure TForm1.btn1Click(Sender: TObject);
var
Stream : TFileStream;
fn : string;
fname : string;
Size : Integer;
Buffer : TBytes;
Encoding : TEncoding;
begin
fn := ExtractFilePath(Application.ExeName) + 'config.dat';
try
Stream := TFileStream.Create(fn, fmCreate);
Stream.Position := 0;
fname := '這是一個測試';
Encoding := TEncoding.Unicode;
Buffer := Encoding.GetBytes(fname);
Size := Length(Buffer);
Stream.WriteBuffer(Pointer(Buffer)^, Size);
finally
Stream.Free;
end;
end;
// 讀取中文
procedure TForm1.btn2Click(Sender: TObject);
var
Stream : TFileStream;
fn : string;
fname : string;
Size : Integer;
Buffer : TBytes;
Encoding : TEncoding;
begin
fn := ExtractFilePath(Application.ExeName) + 'config.dat';
try
Stream := TFileStream.Create(fn, fmOpenRead);
Stream.Position := 0;
// fname := '這是一個測試';
// Encoding := TEncoding.Unicode;
// Buffer := Encoding.GetBytes(fname);
// Size := Length(Buffer);
Size := 12;
SetLength(Buffer, Size);
Stream.ReadBuffer(Pointer(Buffer)^, Size);
Size := TEncoding.GetBufferEncoding(Buffer, Encoding);
// fname := Encoding.GetString(Buffer, Size, Length(Buffer) - Size);
fname := WideStringOf(Buffer);
finally
Stream.Free;
end;
end;
摘自 落魄的雞