只要进行相应的编码转换就可以了。
TStrings的LoadFromFile不能正确加载包含#0字符的文件,建议不要用TStrings对像进行Unicode和Utf-8编码的文件进读写。
读文件
procedure TForm1.Button1Click(Sender: TObject);
var
str:string;
wstr:Widestring;
fs:TFileStream;
Len:integer;
begin
fs:= TfileStream.Create('C:/1.txt',fmShareDenyNone or fmOpenRead );
try
Len:= fs.Size;
setLength(str,3);
fs.Read(str[1],3);
if copy(str,1,2) = #$FF#$FE then
begin
//Unicode编码=====================
Wstr:='';
fs.Position:=2;
setLength(str,Len-2);
fs.Read(str[1],Len-2);
if (Length(str) >= 2) then
begin
setLength(wstr,Length(str)div 2 + Length(str)mod 2);
Move(str[1],wstr[1],Length(str));
end;
Memo1.Text := Wstr;
exit;
end else if str = #$EF#$BB#$BF then
begin
//UTF8编码========================
setLength(str,Len-3);
fs.Read(str[1],Len-3);
Memo1.Text := Utf8ToAnsi(str);
exit;
end;
//ANSI编码============================
fs.Position:=0;
setLength(str,Len);
fs.Read(str[1],Len);
memo1.Text := str;
finally
fs.Free;
end;
end;
写文件
procedure TForm1.Button2Click(Sender: TObject);
var
str:string;
wstr:Widestring;
utf8:Utf8string;
fs:TFileStream;
i,Len:integer;
begin
fs:= TfileStream.Create('C:/1.txt',fmShareDenyNone or fmOpenReadwrite );
try
setLength(str,3);
fs.Read(str[1],3);
if copy(str,1,2) = #$FF#$FE then
begin
//Unicode编码=====================
fs.Position := 2;
wstr:= memo1.text;
if wstr <> '' then
fs.Write(wstr[1],Length(wstr)*sizeof(widechar));
fs.Size := fs.Position;
exit;
end else if str = #$EF#$BB#$BF then
begin
//UTF8编码========================
fs.Position := 3;
utf8:= Ansitoutf8(memo1.Text);
if utf8 <> '' then
fs.Write(utf8[1],Length(utf8));
fs.Size := fs.Position;
exit;
end;
//ANSI编码============================
fs.Position:=0;
if memo1.Text <> '' then
fs.Write(memo1.Text[1],Length(memo1.Text));
fs.Size := fs.Position;
finally
fs.Free;
end;
end;