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