2019-01-15

【Delphi7】讀取 UTF-8 文字檔

參考資料 ----

BOM

 

 

Delphi 預設讀取 ASCII 文字檔,若要讀取 UTF-8 格式的文字檔,則需要轉換。

Form1 上放一個 buttonmemo,然後在 button onclick event 寫入以下程式碼:


  1.  
  2. procedure TForm1.Button1Click(Sender: TObject);
  3. var
  4. myfile: TextFile;
  5. ss: string;
  6. begin
  7. memo1.clear;
  8.  
  9. AssignFile(myfile, 'd:\temp\list.csv');
  10. Reset(myfile);
  11.  
  12. while not EOF(myfile) do
  13. begin
  14. ReadLn(myfile,ss);
  15. // 由於某些 UTF-8 格式的檔首會含有 BOM
  16. // 但 BOM 對 UTF-8 文字檔並非必需
  17. // 因此將 BOM 字元消除
  18. if (pos(#$EF#$BB#$BF,ss)>0) then
  19. begin
  20. ss := StringReplace(ss, #$EF#$BB#$BF, '', [rfReplaceAll]);
  21. end;
  22. ss := UTF8ToAnsi(ss);
  23. memo1.Lines.Add(ss);
  24. end;
  25.  
  26. CloseFile(myfile);
  27. end;
  28.  

相關筆記 ----

【Delphi7】儲存寫入 UTF-8 文字檔