micheal
micheal

Reputation: 197

How to save string into text files in Delphi?

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

Upvotes: 11

Views: 35242

Answers (6)

Vector
Vector

Reputation: 11703

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....

Upvotes: 1

Lars Frische
Lars Frische

Reputation: 329

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);

Upvotes: 6

user160694
user160694

Reputation:

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.

Upvotes: 2

Wim ten Brink
Wim ten Brink

Reputation: 26682

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.

Upvotes: 6

Edelcom
Edelcom

Reputation: 5058

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;

Upvotes: 4

Jens Mühlenhoff
Jens Mühlenhoff

Reputation: 14873

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).

Upvotes: 17

Related Questions