Delphi读取和写⼊utf-8编码格式的⽂件
读取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);
unicode文件格式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;
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论