我需要从另一个应用程序不断更改的.log文件中读取. (经常添加更多数据) 所以我从头开始: var LogFile: TStrings; Stream: TStream; begin LogFile := TStringList.Create; try Stream := TFileStream.Create(Log, fmOp
所以我从头开始:
var LogFile: TStrings; Stream: TStream; begin LogFile := TStringList.Create; try Stream := TFileStream.Create(Log, fmOpenRead or fmShareDenyNone); try LogFile.LoadFromStream(Stream); finally Stream.Free; end; while LogFile.Count > Memo1.Lines.Count do Memo1.Lines.Add(LogFile[Memo1.Lines.Count]); finally LogFile.Free; end; end;
这完全没问题.它会在添加数据的同时实时更新备忘录.但是,我想要在备忘录中看到一些添加的数据.我希望不添加这些行,但仍然可以在没有垃圾线的情况下实时更新备忘录.
最好的方法是什么?
您显然需要检查该行是否包含您要包含的内容,并且仅在具有该内容时添加该内容(如果您不想包含该内容,则不添加它,无论哪种情况).跟踪之前处理的LogFile中的最后一行也会更有效率,因此每次都可以跳过这些行 – 如果您将变量设置为表单本身的私有成员,它将自动初始化为0当你的申请开始时:type TForm1 = class(TForm) //... other stuff added by IDE private LastLine: Integer; end; // At the point you need to add the logfile to the memo for i := LastLine to LogFile.Count - 1 do begin if ContentWanted(LogFile[i]) then Memo1.Lines.Append(LogFile[i]); Inc(LastLine); end;
所以要完全根据你的代码处理这个问题:
type TForm1 = class(TForm) //... IDE stuff here private FLastLogLine: Integer; procedure ProcessLogFile; public // Other stuff end; procedure TForm1.ProcessLogFile; var Log: TStringList; LogStream: TFileStream; i: Integer; begin Log := TStringList.Create; try LogStream := TFileStream.Create(...); try Log.LoadFromStream(LogStream); finally LogStream.Free; end; for i := FLastLogLine to Log.Count - 1 do if Pos('[Globals] []', Log[i]) <>0 then Memo1.Lines.Append(Log[i]); // We've now processed all the lines in Log. Save // the last line we processed as the starting point // for the next pass. FLastLogLine := Log.Count - 1; finally Log.Free; end; end; procedure TForm1.Timer1Timer(Sender: TObject); begin Timer1.Enabled := False; try ProcessLogFile; finally Timer1.Enabled := True; end; end; end;