function LoadUTF8File(FileName: string): string;
var
SS: TStringStream;
begin
SS := TStringStream.Create('', TEncoding.UTF8);
SS.LoadFromFile(FileName);
Result := SS.DataString;
end;
procedure SaveUTF8File(Content:string;FileName: string);
var
SS: TStringStream;
begin
SS := TStringStream.Create('', TEncoding.UTF8);
SS.WriteString(Content);
SS.SaveToFile(FileName);
SS.Free;
end;
Delphi 2010 以前
// UTF8带 BOM
procedure SaveUTF8FileB(AContent:string;AFileName: string);
var ffileStream:TFileStream;
futf8Bytes: string;
S: string;
begin
ffileStream:=TFileStream.Create(AFileName,fmCreate);
futf8Bytes:= UTF8Encode(AContent);
S:=#$EF#$BB#$BF;
ffileStream.Write(S[1],Length(S));
ffileStream.Write(futf8Bytes[1],Length(futf8Bytes));
ffileStream.Free;
end;
// UTF8无BOM
procedure SaveUTF8File(AContent:string;AFileName: string);
var
sFile:TFileStream;
utf8Bytes: string;
s: string;
begin
sFile:=TFileStream.Create(AFileName,fmCreate);
utf8Bytes:= UTF8Encode(AContent);
sFile.Write(s[1],Length(s));
sFile.Write(utf8Bytes[1],Length(utf8Bytes));
sFile.Free;
end;