TWriter (Delphi)

From RAD Studio Code Examples
Jump to: navigation, search

Description

This code example indicates how to use the TWriter class in order to write to a file using streams.

Code

uses
  System.SysUtils, System.Classes;
 
const
  myString = 'This is a set of code examples illustrating the usage of TReader and TWriter';
  anotherString = 'This is another line';
  anotherStringTwo = 'And another line';
 
var
  FileStream: TFileStream;
  Writer: TWriter;
  myStringBuilder: TStringBuilder;

begin
  { Create the TFileStream object and the TWriter used to write data into files. }
  FileStream := TFileStream.Create('C:\Users\Public\Documents\Embarcadero\Studio\stream.txt',
    fmCreate or fmOpenWrite or fmShareDenyNone);
  try
    { $FF = 255. Used in creating the TWriter object as the second parameter : Buffer size. }
    Writer := TWriter.Create(FileStream, $FF);
    try
      { Create the string builder }
      myStringBuilder := TStringBuilder.Create;
      try
        { Append content to the string builder }
        myStringBuilder.Append(myString);
        myStringBuilder.AppendLine;
        myStringBuilder.Append(anotherString);
        myStringBuilder.AppendLine;
        myStringBuilder.Append(anotherStringTwo);
 
        { Commence writing to file }
        Writer.WriteListBegin;
        Writer.WriteString(myStringBuilder.ToString);
        Writer.WriteListEnd;
      finally
        myStringBuilder.Free;
      end;
    finally
      Writer.Free;
    end;
  finally
    FileStream.Free;
  end;
end.

Uses


See Also