当前位置 : 主页 > 编程语言 > delphi >

Delphi读取和写入utf-8编码格式的文件

来源:互联网 收集:自由互联 发布时间:2021-06-23
读取UTF-8格式的文件内容 function LoadUTF8File(AFileName: string ): string ; var ffileStream:TFileStream; fAnsiBytes: string ; S: string ; begin ffileStream: =TFileStream. Create (AFileName,fmOpenRead); SetLength(S,ffileStream.Size)

读取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;

利用delphi自带的UTF8Encode函数,将普通字符转换为utf-8编码

创建一个流,MemoryStream或FileStream都可

函数看起来如下


引用

procedure SaveUTF8File(AContent:WideString;AFileName: string); 
var 
  ffileStream:TFileStream; 
  futf8Bytes: string; 
  S: string; 
begin 
  ffileStream:=TFileStream.Create(AFileName,fmCreate); 
  futf8Bytes:= UTF8Encode(AContent); 
  ffileStream.Write(futf8Bytes[1],Length(futf8Bytes)); 
  ffileStream.Free; 
end;

 


运行后查看生成的文件,全是乱码,上网搜索发现

unicode文本文件:头两个字符分别是FF   FE(16进制) 
utf-8文本文件:头两个字符分别是EF   BB(16进制)

原来是忘了把文件头加进去了

于是加入代码后

procedure SaveUTF8File(AContent:WideString;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;

保存文件后查看,还是乱码。找了半天问题最后终于发现问题出现在声明的参数WideString上,改成string就没问题了。

最后生成 的代码如下

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;

再附上一段读取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;
网友评论