频道分类

Delphi TStreamReader TFile AssignFile读取文本文件

作者:admin 来源: 日期:2020/9/30 10:34:13 人气: 标签:

 

在Delphi中有多种读取文本文件的方法,但是有优点和缺点,因此请根据情况正确使用它们。我认为使用TStreamReader或TFile是正常的,但是存在无法读取锁定文件的问题。 

TStreamReaderTFileAssignFile
读取锁定的文件××
读取锁定的文件×
逐行读取×
字符码支持
从头开始重读(重置)××


 关于编码

TStreamReaderTFileAssignFile
Ascii
SJIS
UTF-8(无BOM)×
UTF-8(有BOM)×

StreamReader使用例
  try
    sr := TStreamReader.Create(filename);
    str := sr.ReadToEnd();       
    while not sr.EndOfStream do  
    begin
      line := sr.ReadLine;  
    end;
  except
    on e: Exception do
    begin
      ShowMessage('ERROR:' + e.Message);
      exit;
    end;
  end;
  sr.Free();
  sl := TStringList.Create();
  sl.Text := str; 
        
TFile使用例
  try
    str := TFile.ReadAllText(filename);   //全文string
    sa  := TFile.ReadAllLines(filename);  //全文TStringDynArray
  except
    on e: Exception do
    begin
      ShowMessage('ERROR:' + e.Message);
      exit;
    end;
  end;

AssignFile使用例
  AssignFile(f, filename);
  try
    Reset(f);
  except
    on e: Exception do
    begin
      ShowMessage('ERROR:' + e.Message);
      exit;
    end;
  end;
  while not Eof(f) do
  begin
    ReadLn(f, line);     //一行
  end;
  CloseFile(f);