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加载图像存储到数据库中

Delphi idhttp超时重定向

Delphi xe10.2 firedac 三种连接

Delphi 关于禁止程序重复启动的另一种需要与实现

Delphi使程序的窗口出现在最前面并激活

Delphi 一个call应该如何写?

Delphi 时间与相关类型(3): tfiletime、tsystemtime 及 dos 时间

Delphi adoquery查询,如何得到查询记录数?

Delphi将excel导入access

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



打赏

取消

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

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

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

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

评论

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