我需要读取另一个应用程序不断更改的.log文件。 (更多数据被频繁添加)
因此,我首先要开始:
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;