[英]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. 假设我有两个文本文件(.txt),我有一个包含一个TMemo组件的表单。 What would be the best way to quickly load both text files into the same Memo?
将两个文本文件快速加载到同一个Memo中的最佳方法是什么?
Use a TStringList
to load each file and then use the AddStrings
method to transfer the contents to the memo. 使用
TStringList
加载每个文件,然后使用AddStrings
方法将内容传输到备忘录。
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 generalised 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;
You could then use the method like so: 然后你可以使用这样的方法:
Memo1.Lines.Clear;
AppendMultipleTextFiles(Memo1.Lines, [FileName1, FileName2]);
Something like this : 像这样的东西:
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;
Without any TStringList: 没有任何TStringList:
uses System.IOUtils;
Memo1.Text := TFile.ReadAllText('1.txt') + #13#10 + TFile.ReadAllText('2.txt');
When you assign string with line breaks to TStrings.Text, this string will be automatically splitted into multiple strings, what can be proven with a following console program: 当您将带有换行符的字符串分配给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.
When setting Text, the value will be parsed by separating into substrings whenever a carriage return or linefeed is encountered.
设置Text时,只要遇到回车符或换行符,就会通过分隔为子字符串来解析该值。 (The two do not need to form pairs).
(两者不需要形成对)。
This method improves readability, but consumes big amount of memory. 此方法提高了可读性,但消耗大量内存。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.