// UTF-8文件写入函数
procedure SaveUTFFile(const FileName: string; S: string; WriteHeader: Boolean = True);varMemStream: TMemoryStream;HeaderStr: String;beginif S = '' then Exit; MemStream := TMemoryStream.Create;tryif WriteHeader thenbeginHeaderStr:=#$EF#$BB#$BF;MemStream.Write(HeaderStr[1], 3);end; S := AnsiToUtf8(S);MemStream.Write(S[1], Length(S));MemStream.Position := 0; MemStream.SaveToFile(FileName);finallyMemStream.Free;end;end;// UtF-8文件读取函数function LoadUTFFile(const FileName: string; ReadHeader: Boolean = True): string;varMemStream: TMemoryStream;S, HeaderStr:string;beginResult:='';if not FileExists(FileName) then Exit;MemStream := TMemoryStream.Create;tryMemStream.LoadFromFile(FileName);if ReadHeader thenbeginSetLength(HeaderStr, 3);MemStream.Read(HeaderStr[1], 3); if HeaderStr = #$EF#$BB#$BF thenbeginSetLength(S, MemStream.Size - 3);MemStream.Read(S[1], MemStream.Size - 3);end;end elsebeginSetLength(S, MemStream.Size);MemStream.Read(S[1], MemStream.Size);end;Result := Utf8ToAnsi(S);finallyMemStream.Free;end;end;// Unicode文件写入函数procedure SaveUnicodeFile(const FileName:string; const S: string; WriteHeader: Boolean = True);varMemStream: TMemoryStream;HeaderStr: string;WStr: WideString;beginif S = '' then exit;MemStream := TMemoryStream.Create;tryif WriteHeader thenbeginHeaderStr := #$FF#$FE;MemStream.Write(HeaderStr[1], 2);end;WStr := WideString(S);MemStream.Write(WStr[1], Length(WStr)*2);MemStream.Position := 0;MemStream.SaveToFile(FileName);finallyMemStream.Free;end;end;// Unicode文件读取函数function LoadUnicodeFile(const FileName: string; ReadHeader: Boolean = True): string;varMemStream: TMemoryStream;FlagStr: String;WStr: WideString;beginResult := '';if not FileExists(FileName) then Exit;MemStream := TMemoryStream.Create;tryMemStream.LoadFromFile(FileName); if ReadHeader thenbeginSetLength(FlagStr, 2);MemStream.Read(FlagStr[1], 2);if FlagStr = #$FF#$FE thenbeginSetLength(WStr, (MemStream.Size-2) div 2);MemStream.Read(WStr[1], MemStream.Size - 2);end;end elsebeginSetLength(WStr, MemStream.Size div 2);MemStream.Read(WStr[1], MemStream.Size);end;Result := AnsiString(WStr);finallyMemStream.Free;end;end;//保存文件procedure savetofile(const FileName:string; const S: string);varF: TextFile;beginAssignFile(F, FileName); // 将文件与F变量建立连接,后面可以使用F变量对文件进行操作。Rewrite(F); // 以追加的方式打开文件Writeln(F, S); // 将S变量中的内容追加到文本尾后。CloseFile(F); // 关闭文件end