Delphi中如何将字符串保存到文本文件中?

发布于 2024-10-02 12:32:09 字数 50 浏览 8 评论 0原文

创建字符串并将其保存到 .txt 文件中的最简单方法是什么?

What is the easiest way to create and save string into .txt files?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

£噩梦荏苒 2024-10-09 12:32:09

使用TStringList

uses
  Classes, Dialogs; // Classes for TStrings, Dialogs for ShowMessage

var
  Lines: TStrings;
  Line: string;
  FileName: string;
begin
  FileName := 'test.txt';
  Lines := TStringList.Create;
  try
    Lines.Add('First line');
    Lines.Add('Second line');
    Lines.SaveToFile(FileName);
    Lines.LoadFromFile(FileName);
    for Line in Lines do
      ShowMessage(Line);
  finally
    Lines.Free;
  end;
end;

另外,SaveToFileLoadFromFile 可以在 Delphi 2009 及更高版本中采用额外的编码来设置文本编码(Ansi、UTF-8、UTF-16、UTF-16 big endian) 。

Use TStringList.

uses
  Classes, Dialogs; // Classes for TStrings, Dialogs for ShowMessage

var
  Lines: TStrings;
  Line: string;
  FileName: string;
begin
  FileName := 'test.txt';
  Lines := TStringList.Create;
  try
    Lines.Add('First line');
    Lines.Add('Second line');
    Lines.SaveToFile(FileName);
    Lines.LoadFromFile(FileName);
    for Line in Lines do
      ShowMessage(Line);
  finally
    Lines.Free;
  end;
end;

Also SaveToFile and LoadFromFile can take an additional Encoding in Delphi 2009 and newer to set the text encoding (Ansi, UTF-8, UTF-16, UTF-16 big endian).

残疾 2024-10-09 12:32:09

实际上,我更喜欢这个:

var
  Txt: TextFile;
  SomeFloatNumber: Double;
  SomeStringVariable: string;
  Buffer: Array[1..4096] of byte;
begin
  SomeStringVariable := 'Text';
  AssignFile(Txt, 'Some.txt');
  Rewrite(Txt);
  SetTextBuf(Txt, Buffer, SizeOf(Buffer));
  try
    WriteLn(Txt, 'Hello, World.');
    WriteLn(Txt, SomeStringVariable);
    SomeFloatNumber := 3.1415;
    WriteLn(Txt, SomeFloatNumber:0:2); // Will save 3.14
  finally CloseFile(Txt);
  end;
end;

我认为这是最简单的方法,因为您不需要此代码的类或任何其他单元。它适用于所有 Delphi 版本,包括 - 如果我没记错的话 - 所有 .NET 版本的 Delphi...


我在这个示例中添加了对 SetTextBuf() 的调用,这是加速 Delphi 中文本文件速度的好技巧相当。通常,文本文件的缓冲区只有 128 字节。我倾向于将此缓冲区增加到 4096 字节的倍数。在某些情况下,我还实现了自己的 TextFile 类型,允许我使用这些“控制台”函数将文本写入备注字段,甚至写入另一个外部应用程序! 这个位置是我在 2000 年编写的一些示例代码 (ZIP),只是进行了修改以确保它可以编译使用 Delphi 2007。不过不确定较新的 Delphi 版本。话又说回来,这段代码已经有 10 年历史了。
这些控制台函数自 Pascal 语言诞生以来就一直是它的标准,所以我不认为它们会很快消失。不过,TtextRec 类型将来可能会被修改,所以我无法预测这段代码将来是否会工作...一些解释:

  • WA_TextCustomEdit.AssignCustomEdit 允许将文本写入基于 CustomEdit 的对象,如 TMemo。
  • WA_TextDevice.TWATextDevice 是一个可以放在表单上的类,其中包含可以对写入的数据执行某些操作的事件。
  • 我使用 WA_TextLog.AssignLog 为每一行文本添加时间戳。
  • WA_TextNull.AssignNull 基本上是一个虚拟文本设备。它只是丢弃您写入的任何内容。
  • WA_TextStream.AssignStream 将文本写入任何 TStream 对象,包括内存流、文件流、TCP/IP 流以及您拥有的任何其他对象。

链接中的代码特此许可为 CC-BY alt text


哦,带有 ZIP 文件的服务器不是很强大,所以每天都会宕机几次。对此感到抱歉。

Actually, I prefer this:

var
  Txt: TextFile;
  SomeFloatNumber: Double;
  SomeStringVariable: string;
  Buffer: Array[1..4096] of byte;
begin
  SomeStringVariable := 'Text';
  AssignFile(Txt, 'Some.txt');
  Rewrite(Txt);
  SetTextBuf(Txt, Buffer, SizeOf(Buffer));
  try
    WriteLn(Txt, 'Hello, World.');
    WriteLn(Txt, SomeStringVariable);
    SomeFloatNumber := 3.1415;
    WriteLn(Txt, SomeFloatNumber:0:2); // Will save 3.14
  finally CloseFile(Txt);
  end;
end;

I consider this the easiest way, since you don't need the classes or any other unit for this code. And it works for all Delphi versions including -if I'm not mistaken- all .NET versions of Delphi...


I've added a call to SetTextBuf() to this example, which is a good trick to speed up textfiles in Delphi considerably. Normally, textfiles have a buffer of only 128 bytes. I tend to increase this buffer to a multiple of 4096 bytes. In several cases, I'va also implemented my own TextFile types, allowing me to use these "console" functions to write text to memo fields or even to another, external application! At this location is some example code (ZIP) I wrote in 2000 and just modified to make sure it compiles with Delphi 2007. Not sure about newer Delphi versions, though. Then again, this code is 10 years old already.
These console functions have been a standard of the Pascal language since it's beginning so I don't expect them to disappear anytime soon. The TtextRec type might be modified in the future, though, so I can't predict if this code will work in the future... Some explanations:

  • WA_TextCustomEdit.AssignCustomEdit allows text to be written to CustomEdit-based objects like TMemo.
  • WA_TextDevice.TWATextDevice is a class that can be dropped on a form, which contains events where you can do something with the data written.
  • WA_TextLog.AssignLog is used by me to add timestamps to every line of text.
  • WA_TextNull.AssignNull is basically a dummy text device. It just discards anything you write to it.
  • WA_TextStream.AssignStream writes text to any TStream object, including memory streams, file streams, TCP/IP streams and whatever else you have.

Code in link is hereby licensed as CC-BY alt text


Oh, the server with the ZIP file isn't very powerful, so it tends to be down a few times every day. Sorry about that.

枯叶蝶 2024-10-09 12:32:09

Delphi 2010中引入的IOUtils单元提供了一些非常方便的用于写入/读取文本文件的函数:

//add the text 'Some text' to the file 'C:\users\documents\test.txt':
TFile.AppendAllText('C:\users\documents\text.txt', 'Some text', TEncoding.ASCII);

The IOUtils unit which was introduced in Delphi 2010 provides some very convenient functions for writing/reading text files:

//add the text 'Some text' to the file 'C:\users\documents\test.txt':
TFile.AppendAllText('C:\users\documents\text.txt', 'Some text', TEncoding.ASCII);
初雪 2024-10-09 12:32:09

或者,如果您使用旧版本的 Delphi(它没有迭代字符串列表的 for line inlines 方法):

var i : integer;
begin

...
try
    Lines.Add('First line');
    Lines.Add('Second line');
    Lines.SaveToFile(FileName);
    Lines.LoadFromFile(FileName);
    for i := 0 to Lines.Count -1 do
      ShowMessage(Lines[i]);
  finally
    Lines.Free;
  end;

Or if you are using an older version of Delphi (which does not have the for line in lines method of iterating a string list):

var i : integer;
begin

...
try
    Lines.Add('First line');
    Lines.Add('Second line');
    Lines.SaveToFile(FileName);
    Lines.LoadFromFile(FileName);
    for i := 0 to Lines.Count -1 do
      ShowMessage(Lines[i]);
  finally
    Lines.Free;
  end;
清醇 2024-10-09 12:32:09

如果您使用的 Delphi 版本 >= 2009,请查看 TStreamWriter 类。

它还将处理文本文件编码和换行符。

If you're using a Delphi version >= 2009, give a look to the TStreamWriter class.

It will also take care of text file encodings and newline characters.

抽个烟儿 2024-10-09 12:32:09
procedure String2File;
var s:ansiString;
begin
    s:='My String';
    with TFileStream.create('c:\myfile.txt',fmCreate) do
    try
      writeBuffer(s[1],length(s));
    finally
      free;
    end;
end;

使用 unicode 字符串时需要小心......

procedure String2File;
var s:ansiString;
begin
    s:='My String';
    with TFileStream.create('c:\myfile.txt',fmCreate) do
    try
      writeBuffer(s[1],length(s));
    finally
      free;
    end;
end;

Care needed when using unicode strings....

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文