Delphi TStreamReader TFile AssignFile读取文本文件


本文整理自网络,侵删。

 

在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); 

相关阅读 >>

Delphi 通过递归来实现搜索文件

Delphi 内存管理[3]

Delphi 如何编写使stringgrid中的一列具有check功能,和checkbox效果一样

Delphi image 等比例缩小

Delphi dos编程

Delphi dbgrid查询内容的导出为txt函数

Delphi 删除cookies及上网记录

Delphi xe5 android listview

Delphi 读取utf-8格式的文件内容

Delphi 得到执行程序的当前所在完整路径

更多相关阅读请进入《Delphi》频道 >>



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...