Delphi读写UTF-8、Unicode格式文本文件


本文整理自网络,侵删。

 Delphi读写UTF-8、Unicode格式文本文件

在研究PvPGN时发现conf配置文件一些为UTF-8和Unicode格式,这样便可良好的支持多语言,从网上查阅资料后,将读写UTF-8、Unicode文件写了几个最精简的函数,更新后加了是否写文件头的功能,以适应更多需要,注意函数未加防错保护。

参数说明:f文件名、s写入或读取的文件内容、hs文件头、b是否读写文件头。

UTF-8文件写入函数



程序代码

procedure SaveUTF(f:string;s:string;b:boolean=true);
var
ms:TMemoryStream;
hs:String;
begin
if s='' then exit;
ms:=TMemoryStream.Create;
if b then begin
hs:=#$EF#$BB#$BF;
ms.Write(hs[1],3);
end;
s:=AnsiToUtf8(s);
ms.Write(s[1],Length(s));
ms.Position:=0;
ms.SaveToFile(f);
ms.Free;
end;



UtF-8文件读取函数



程序代码

function LoadUTF(f:string;b:boolean=true):string;
var
ms:TMemoryStream;
s,hs:string;
begin
Result:='';
if not FileExists(f) then exit;
ms:=TMemoryStream.Create;
ms.LoadFromFile(f);
if b then begin
SetLength(hs,3);
ms.Read(hs[1],3);
if hs<>#$EF#$BB#$BF then begin ms.Free; exit; end;
SetLength(s,ms.Size-3);
ms.Read(s[1],ms.Size-3);
end else begin
SetLength(s,ms.Size);
ms.Read(s[1],ms.Size);
end;
Result:=Utf8ToAnsi(s);
ms.Free;
end;



Unicode文件写入函数



程序代码

procedure SaveUnicode(f:string;s:string;b:boolean=true);
var
ms:TMemoryStream;
hs:string;
ws:WideString;
begin
if s='' then exit;
ms:=TMemoryStream.Create;
if b then begin
hs:=#$FF#$FE;
ms.Write(hs[1],2);
end;
ws:=WideString(s);
ms.Write(ws[1],Length(ws)*2);
ms.Position:=0;
ms.SaveToFile(f);
ms.Free;
end;



Unicode文件读取函数



程序代码

function LoadUnicode(f:string;b:boolean=true):string;
var
ms:TMemoryStream;
hs:String;
ws:WideString;
begin
Result:='';
if not FileExists(f) then exit;
ms:=TMemoryStream.Create;
ms.LoadFromFile(f);
if b then begin
SetLength(hs,2);
ms.Read(hs[1],2);
if hs<>#$FF#$FE then begin ms.Free; exit; end;
SetLength(ws,(ms.Size-2) div 2);
ms.Read(ws[1],ms.Size-2);
end else begin
SetLength(ws,ms.Size div 2);
ms.Read(ws[1],ms.Size);
end;
Result:=AnsiString(ws);
ms.Free;
end;

相关阅读 >>

Delphi 如何使用findfirst搜索不同的文件类型?

Delphi 内存管理[6]

Delphi embeddedwb 遍历frames并执行子frame的js脚本

Delphi 关于使用access中带参数的查询的用法

Delphi sysutils.comparestr、sysutils.comparetext - 字符串比较

Delphi tstringlist.find

Delphi 如何使用通配符删除文件

Delphi firedac 另存json

Delphixe ansi字符串utf-8编码判断

Delphi 锁定系统解锁系统

更多相关阅读请进入《Delphi》频道 >>



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...