我需要读取由另一个应用程序不断更改的 .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 中的最后一行也会更有效,因此您每次都可以跳过这些行 - 如果您将变量设置为表单本身的私有(private)成员,当您的应用程序启动时,它会自动初始化为 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;
关于Delphi - 从每秒更改的日志文件中读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24015215/