簡體   English   中英

如何讀取大小未知的未知類型文件

[英]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對象正常工作,還是應該使用其他方法?

我需要讀取未知類型和大小文件的內容,並將其保存到字符串中。

由於您要將其保存為字符串,因此

  1. 該文件是文本文件,或者
  2. 您做錯了(字符串只能存儲文本數據)。

假設第一個選項,您只需

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

uses IOUtils )。

還可以使用ReadAllText重載來指定編碼(例如,UTF-8或UTF-16LE)。

更新。 該問題已編輯,現在顯示為

我需要讀取未知類型和大小文件的內容並保存。

您是否只想復制文件? 如果是這樣,則可以使用任何可用的文件復制方法,例如CopyFile Win32函數, TFile.Copy的TFile.Copy等。

還是要獲取文件的字節以便可以在應用程序中處理它? 如果是這樣,我的原始答案很接近您的需求。 只需使用ReadAllBytes而不是ReadAllText

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

其中, MyDynamicByteArray動態字節數組TArray<Byte> ,即array of byte )。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM