What is the best way to load two text files into one TMemo component in Delphi?

Let's say I have two text files (.txt), and I have a form with one TMemo component on it. What would be the best way to quickly load both text files into the same Memo?

+4
source share
3 answers

Use TStringListto download each file, and then use the method AddStringsto transfer content to the memo.

var
  Tmp: TStringList;
...
Memo1.Lines.BeginUpdate;
try
  Memo1.Lines.Clear;
  Tmp := TStringList.Create;
  try
    Tmp.LoadFromFile(FileName1);
    Memo1.Lines.AddStrings(Tmp);

    Tmp.LoadFromFile(FileName2);
    Memo1.Lines.AddStrings(Tmp);
  finally
    Tmp.Free;
  end;
finally
  Memo1.Lines.EndUpdate;
end;

In fact, this can easily be generalized to a potentially useful method like this:

procedure AppendMultipleTextFiles(Dest: TStrings; const FileNames: array of string);
var
  FileName: string;
  Tmp: TStringList;
begin
  Dest.BeginUpdate;
  try
    Tmp := TStringList.Create;
    try
      for FileName in FileNames do
      begin
        Tmp.LoadFromFile(FileName);
        Dest.AddStrings(Tmp);
      end;
    finally
      Tmp.Free;
    end;
  finally
    Dest.EndUpdate;
  end;
end;

Then you can use the method as follows:

Memo1.Lines.Clear;
AppendMultipleTextFiles(Memo1.Lines, [FileName1, FileName2]);
+9
source

Something like that:

sl := TstringList.Create;
try
  sl.LoadFromFile('1.TXT');
  memo1.Lines.Add(sl.Text);

  sl.Clear;
  sl.LoadFromFile('2.TXT');
  memo1.Lines.Add(s2.Text);


finally
  sl.Free
end;
+1
source

TStringList:

uses System.IOUtils;

Memo1.Text := TFile.ReadAllText('1.txt') + #13#10 + TFile.ReadAllText('2.txt');

TStrings.Text, , :

program Project1;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils,
  System.Classes,
  System.IOUtils;

var StringList: TStringList;
    s: string;
begin
  try
    StringList := TStringList.Create;
    StringList.Text := TFile.ReadAllText('1.txt');
    for s in StringList do
      begin
        Writeln(s);
        Writeln('-----');
      end;
    Readln;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.

docwiki

When setting up the text, the value will be analyzed by dividing into substrings whenever there is a carriage return or line feed. (These two do not need to create pairs).

This method improves readability, but consumes a large amount of memory.

0
source

Source: https://habr.com/ru/post/1688049/


All Articles