2015年8月13日 星期四

[Delphi] 使用TStringList讀取UTF-8編碼的文件

一開始我是用AssignFile方式讀取一份文字檔,在ANSI編碼的時候還算順利,如下:
procedure MyClass.ReadAnsiFile;
var
  f : TextFile;
  line : String;
begin
  AssignFile(f, 'C:\temp\myFile.txt');
  Reset(f);
  line := '';
 
  While not Eof(f) do
  begin
    ReadLn(f, line);
  end;
  CloseFile(f);
end;

每行印出來都很正常,但是當我將這個檔案換成UTF-8編碼時(不管有沒有BOM),他只要遇到中文字就變成亂碼了,所以我必須換個寫法
(假設我已經知道要讀取的文件是UTF-8格式)

procedure MyClass.ReadUtf8File;
var
  strList : TStringList;
  I : Integer;
  line := '';
begin
  strList := TStringList.Create;
  stringList.LoadFromFile('C:\temp\myFile2.txt', TEncoding.UTF8);
  for I := 0 to strList.Count - 1 do
  begin
    line := strList[I];
  end;
end;

關鍵就在strList.LoadFromeFile(path, TEncoding.UTF8)
有API可以呼叫當然就使用它,這樣會省事多了

沒有留言: