如何读取未知大小的未知类型文件

How to read an unknown type file of unknown size

我需要读取一个未知类型和大小的文件的内容并临时保存(在某种变量中),以便稍后通过串口传输时使用它。据我了解,TFileStream 是正确的方法。

我确实尝试实施 http://docwiki.embarcadero.com/CodeExamples/Tokyo/en/TReader_(Delphi)

中的以下教程
unit Unit1;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Utils;

type
  TForm1 = class(TForm)
    procedure OnCreate(Sender: TObject);

    private
      selectedFile: string;
  end;

var
  Form1: TForm1;

implementation
{$R *.dfm}

procedure TForm1.OnCreate(Sender: TObject);
  function ReadFileContent(fileName: String): String;
  var
    FileStream: TFileStream;
    Reader: TReader;
    tByte :byte;

  begin

    FileStream := TFileStream.Create(fileName, fmOpenRead);
    Reader := TReader.Create(FileStream, $FF);

    Reader.ReadListBegin;           //I get 'Invalid property Value' error
                                    //in this line raised from the Reader object

    while not Reader.EndOfList do
    begin
      Reader.ReadVar(tByte, 1);
    end;

    Reader.ReadListEnd;

    Reader.Destroy;
    FileStream.Destroy;
  end;

var
  dlg: TOpenDialog;
begin
  selectedFile := '';
  dlg := TOpenDialog.Create(nil);
  try
    dlg.InitialDir := '.\';
    dlg.Filter := 'All files (*.*)|*.*';
    if dlg.Execute(Handle) then
      selectedFile := dlg.FileName;
  finally
    dlg.Free;
end;

if selectedFile <> '' then
  ReadFileContent(selectedFile);
end;
end.

为了让 Reader 对象正常工作,我还需要设置什么吗?或者我应该使用不同的方法?

I need to read the content of an unknown type and size file and save it into a string.

既然你想把它保存在一个字符串中,要么

  1. 文件是文本文件,或者
  2. 你做错了(字符串只能存储文本数据)。

假设第一个选项,你可以简单地做

MyStringVariable := TFile.ReadAllText('C:\myfile.txt');

(uses IOUtils).

还有一个 ReadAllText 的重载,您可以使用它来指定编码(例如,UTF-8 或 UTF-16LE)。

更新。问题已编辑,现在显示为

I need to read the content of an unknown type and size file and save it.

您只想复制文件吗?如果是这样,您可以使用任何可用的文件复制方法,例如 CopyFile Win32 函数、来自 IOUtils 的 TFile.Copy 等等。

或者您想获取文件的字节数以便在您的应用程序中处理它?如果是这样,我的原始答案接近您的需要。只需使用 ReadAllBytes 而不是 ReadAllText:

MyDynamicByteArray := TFile.ReadAllBytes('C:\logo.bmp');

其中 MyDynamicByteArraydynamic array 个字节(TArray<Byte>,即 array of byte)。