AI摘要

本文介绍了如何在Delphi中处理UTF-8编码格式的文件。提供了两个函数:LoadUTF8File用于读取UTF-8文件内容,通过创建文件流、设置长度、读取内容并使用UTF8Decode函数解码;SaveUTF8File用于将内容写入UTF-8文件,通过创建文件流、使用UTF8Encode函数编码内容,并在文件开头添加UTF-8 BOM标记。这两个函数可以帮助开发者在Delphi中方便地读写UTF-8编码的文件。
本文介绍了如何在D

读取UTF-8格式的文件内容

function LoadUTF8File(AFileName: string): string;
var  ffileStream:TFileStream; 
         fAnsiBytes: string;
         S: string;
begin
            ffileStream:=TFileStream.Create(AFileName,fmOpenRead);
            SetLength(S,ffileStream.Size); 
            ffileStream.Read(S[1],Length(S));
            fAnsiBytes:= UTF8Decode(Copy(S,4,MaxInt));
           Result:= fAnsiBytes;
end;

写入UTF-8编码格式的文件
procedure SaveUTF8File(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;



最后修改:2010 年 08 月 18 日
点赞的人是最酷的