首页 > 解决方案 > TFileStream 将数据写入下一行

问题描述

我正在操作 TFileStream 并且我想将数据写入下一行。

以下代码重写了前一个...

我能做些什么来包装并让它在那里写下新的一行?

function TParserSkyecc.GenerateHTMLFile(pathHtml,out1,out2,out3,out4,out5 : String) : Boolean;
var FS: TFileStream;
begin
  FS := TFileStream.Create(pathHtml+'\filename.txt',fmCreate or fmOpenWrite or fmShareDenyNone);
  try
  FS.Seek(0,soFromBeginning);
    FS.WriteBuffer(Pointer(AnsiString(out1))^,Length(out1));
    FS.WriteBuffer(Pointer(AnsiString(out2))^,Length(out2));
    FS.WriteBuffer(Pointer(AnsiString(out3))^,Length(out3));
    FS.WriteBuffer(Pointer(AnsiString(out4))^,Length(out4));
    FS.WriteBuffer(Pointer(AnsiString(out5))^,Length(out5));
  finally
    FS.Free;
  end;
end;

标签: delphidelphi-2010

解决方案


一种更简单的编写方法是使用TStreamWriter而不是TFileStream直接使用。在它的构造函数中TStreamWriter接受 a ,并且有一个方法。例如:TEncodingWriteLine()

function TParserSkyecc.GenerateHTMLFile(pathHtml,out1,out2,out3,out4,out5 : String) : Boolean;
var
  Filename: string;
  Writer: TStreamWriter;
begin
  Result := False;
  try
    Filename := IncludeTrailingPathDelimiter(pathHtml) + 'filename.txt'; // or: TPath.Combine(pathHtml, 'filename.txt')
    Writer := TStreamWiter.Create(Filename, False, TEncoding.ANSI);
    try
      Writer.WriteLine(out1);
      Writer.WriteLine(out2);
      Writer.WriteLine(out3);
      Writer.WriteLine(out4);
      Writer.WriteLine(out5);
      Writer.Flush;
      Result := True;
    finally
      Writer.Free;
    end;
  except
  end;
end;

或者,您可以TStringList改用:

function TParserSkyecc.GenerateHTMLFile(pathHtml,out1,out2,out3,out4,out5 : String) : Boolean;
var
  Filename: string;
  SL: TStringList;
begin
  Result := False;
  try
    Filename := IncludeTrailingPathDelimiter(pathHtml) + 'filename.txt'; // or: TPath.Combine(pathHtml, 'filename.txt')
    SL := TStringList.Create;
    try
      SL.Add(out1);
      SL.Add(out2);
      SL.Add(out3);
      SL.Add(out4);
      SL.Add(out5);
      SL.SaveToFile(Filename, TEncoding.ANSI);
      Result := True;
    finally
      SL.Free;
    end;
  except
  end;
end;

推荐阅读