TBinaryReader and TBinaryWriter (Delphi)

From RAD Studio Code Examples
Jump to: navigation, search

Description

This example shows how to use TBinaryReader and TBinaryWriter.

Code

uses
  SysUtils,
  Classes;

// Using BinaryReader
procedure ReadBinary(filename: string);
var
  AFile: TFileStream;
  BR: TBinaryReader;
  AInteger: Integer;
  ADouble: Double;
  AChar: Char;
  AString: String;
begin
  AFile := TFileStream.Create(filename, fmOpenRead);
  BR := TBinaryReader.Create(AFile, TEncoding.Unicode, false);
  try
    // read an integer and write it to the console
    AInteger := BR.ReadInteger;
    Writeln(AInteger);

    // read a double and write it to the console
    ADouble := BR.ReadDouble;
    Writeln(ADouble);

    // read a char and write it to the console
    AChar := BR.ReadChar;
    Writeln(AChar);
    // read a string and write it to the console
    AString := BR.ReadString;
    Writeln(AString);

    BR.Close;
  finally

    BR.Free;
    AFile.Free;
  end;

end;

// Using BinaryWriter
procedure WriteBinary(filename: string);
var
  AFile: TFileStream;
  BW: TBinaryWriter;
  AInteger: Integer;
  ADouble: Double;
  AChar: Char;
  AString: String;
begin
  AFile := TFileStream.Create(filename, fmOpenWrite or fmCreate);
  BW := TBinaryWriter.Create(AFile, TEncoding.Unicode, false);
  try
    AInteger := 10;
    // write an integer to stream
    BW.Write(AInteger);
    ADouble := 0.34;
    // write a double to stream
    BW.Write(ADouble);
    AChar := 'A';
    // write a char to stream
    BW.Write(AChar);
    // write a string to stream
    AString := 'Hello world!';
    BW.Write(AString);
    BW.Close;
  finally
    BW.Free;
    AFile.Free;
  end;

end;

begin
  try
    WriteBinary('file.dat');
    ReadBinary('file.dat');
    Readln; //wait a char (used to keep the window opened to see the result)
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;

end.

Uses