TBinaryReader and TBinaryWriter

by Radek Červinka 16. October 2010 00:44

There are some new handy classes in every new Delphi version. In Delphi XE e.g. implementation of TBinaryReader and TBinaryWriter.

It is clear that something similar can be programmed in an afternoon, but I am pleased with the original implementation.

As the names suggest, these classes are implementation of a binary writing and reading of the stream (file). Let me give you an example:

    1program Project1;
    2
    3{$APPTYPE CONSOLE}
    4
    5uses
    6  SysUtils, Classes;
    7var
    8  oReader: TBinaryReader;
    9  oWriter: TBinaryWriter;
   10  s: string = 'Temp Text';
   11  s2: string;
   12  d: double = 3.5;
   13begin
   14  s2 := StringOfChar('A', 400);
   15  oWriter := TBinaryWriter.Create('test');
   16  try
   17    oWriter.Write(s); // string
   18    oWriter.Write(byte(1)); // byte
   19    oWriter.Write(True); // boolean
   20    oWriter.Write(d); // double 8byte
   21    oWriter.Write(s2); // string
   22  finally
   23    oWriter.Free;
   24  end;
   25
   26  oReader := TBinaryReader.Create('test');
   27  try
   28    writeln(oReader.ReadString);
   29    writeln(oReader.ReadByte);
   30    writeln(oReader.ReadBoolean);
   31    writeln(oReader.ReadDouble);
   32    writeln(oReader.ReadString);
   33  finally
   34    oReader.Free;
   35  end;
   36end.

Very straightforward.

Personally, I like writing and reading of the the string, where is completely transparently for programmer stored size of string before string data and this size is stored very effective, when for length to 127 bytes (ie, 7 bits, eliminating the problem of reading) is used only a single byte, etc. When you read string you do not solve anything, the string will be loaded correctly.

That's not all. In addition, the constructor can pass encoding which the strings are saved (or loaded). The following code saves the text as UTF8. In addition to the constructor can pass the stream.

    1oWriter := TBinaryWriter.Create('test2', False, TEncoding.UTF8);
    2  try
    3    oWriter.Write('hasta la vista baby');
    4  finally
    5    oWriter.Free;
    6  end;

Online doc: TBinaryWriter and TBinaryReader.

Tags: ,

Delphi news

Comments are closed