0

我需要读取一个未知类型和大小文件的内容并临时保存它(在某种变量中),以便稍后使用它通过串行端口进行传输。据我了解, 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 对象正常工作,我还需要设置什么,或者我应该使用不同的方法吗?

4

1 回答 1

5

我需要读取未知类型和大小文件的内容并将其保存到字符串中。

由于您想将其保存在字符串中,因此

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

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

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

( uses IOUtils)。

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

更新。问题已编辑,现在阅读

我需要读取未知类型和大小文件的内容并保存。

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

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

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

其中MyDynamicByteArray是一个动态字节数组TArray<Byte>,即array of byte)。

于 2019-08-19T11:12:14.107 回答