TReader (Delphi)

From RAD Studio Code Examples
Jump to: navigation, search

Description

This code example indicates how to use the TReader class in order to read from a file using streams.

Note: Check the TWriter (Delphi) code example in order to create the stream.txt file, or feel free to change the path to another existing file.

Code

uses
  System.SysUtils, System.Classes;

var
  FileStream: TFileStream;
  Reader: TReader;
  myStringBuilder: TStringBuilder;

begin
  { Create the TFileStream object and the TReader used to read data from files. }
  FileStream := TFileStream.Create
    ('C:\Users\Public\Documents\RAD Studio\stream.txt', fmOpenRead);
  { $FF = 255. Used in creating the TReader object as the second parameter : Buffer size. }
  Reader := TReader.Create(FileStream, $FF);

  myStringBuilder := TStringBuilder.Create;

  { Commence reading from file }
  Reader.ReadListBegin;
  while not Reader.EndOfList do
    myStringBuilder.Append(Reader.ReadString);
    // You can skip a value in a list by calling Reader.SkipValue
  Reader.ReadListEnd;

  { Print out results }
  writeln(myStringBuilder.ToString);
  readln;

  Reader.Destroy;
  FileStream.Destroy;

end.

Uses


See Also