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,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,MaxInt)); Result:= fAnsiBytes; end;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。