如何将许多小文本文件读取到 Delphi 10 中的数组中?

How do I read many small text files into an array in Delphi 10?

我是 Delphi 的新手。 我开发了一个 VBA 程序,它首先使用下面的代码将许多小文本文件读入一个数组。 我刚开始重写 Delphi 10.3.

中的程序

Delphi中是否有等效代码? 或

欢迎提出建议。

Set fso = CreateObject("scripting.filesystemobject")
Set MyFolder = fso.GetFolder(FileNameSource)
Set MyFileNames = MyFolder.Files

AllCount = MyFolder.Files.Count

ReDim AllMyWeeklyFileContents(1 To AllCount) As string
AllCount = 1
For Each MyFiles In MyFileNames
  AFileName = MyFolder & "\" & MyFiles.Name
  Set MyFileToRead = fso.GetFile(AFileName)
  Set MyFileContent = MyFileToRead.OpenAsTextStream(ForReading, TristateUseDefault)
  AllMyWeeklyFileContents(AllCount) = MyFileContent.ReadAll
  AllCount = AllCount + 1
Next
Set fso = Nothing
Set MyFolder = Nothing

下面是写在Delphi中的等价物。要使用该代码,请创建一个新的 Windows VCL 应用程序,在窗体上放置一个按钮和一个备忘录,然后使用下面的代码作为按钮的 OnClick 事件处理程序。

代码获取给定文件夹中的文件列表,读取每个文件,连接数组中的行。然后迭代数组以显示在备忘录中。

unit ReadManyFilesDemoMain;

interface

uses
    Winapi.Windows, Winapi.Messages,
    System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
    System.IOUtils, System.Types,
    System.Generics.Collections, System.Generics.Defaults,
    Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;

type
    TForm1 = class(TForm)
        Button1: TButton;
        Memo1: TMemo;
        procedure Button1Click(Sender: TObject);
    end;

var
    Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
var
    FileNames : TArray<String>;   // The array for all filenames
    FileName  : String;           // A single filename
    Lines     : TArray<String>;   // The array of all lines
    Line      : String;           // A single line
begin
    // Get all text file names from given path
    FileNames := TDirectory.GetFiles('E:\Temp', '*.txt');
    // For each filename, add his lines to the dynamic array
    for FileName in FileNames do
        Lines := TArray.Concat<String>([Lines, TFile.ReadAllLines(FileName)]);
    // Display in the memo all collected lines
    for Line in Lines do
        Memo1.Lines.Add(Line);
end;

end.

基本上有多个问题:

  • 如何获取特定文件夹中的(文本)文件列表(可能带有特定的文件掩码...)
  • 如何创建动态(字符串)数组将所有文件的内容放入
  • 如何读取文本文件的全部内容

第一个

Files := TDirectory.GetFiles(FolderPath, FileMask);

第二个

SetLength(FileContent, Length(Files));

最后一个(基于 Andreas 评论)

FileContent := TFile.ReadAllText(Filename)

放在一个函数中时:

function GetAllTextFilesContent(const FolderPath, FileMask: string): TArray<string>;
var
  I: integer;
  Files: TArray<string>;
begin
  // list files
  Files := TDirectory.GetFiles(FolderPath, FileMask);
  // set size result array to number of files
  SetLength(Result, Length(Files));
  // read and put file content of each file into the result array
  for I := 0 to Length(Files) - 1 do
    Result[I] := TFile.ReadAllText(Files[I]);
end;

请注意:此例程不检查文件是否实际上是文本文件。当二进制文件是文件掩码的一部分时,您可能会得到一些奇怪的结果!