StreamCharRdWr (Delphi)

From RAD Studio Code Examples
Jump to: navigation, search

Description

This example demonstrates the use of the TStreamReader and TStreamWriter classes. Writing and reading are made byte-by-byte. This example also sets the line endings to be Unix-compatible.

Code

procedure TMainForm.btLoadClick(Sender: TObject);
var
  Reader: TStreamReader;
  Size: Int64;
  Line: String;
  Ch: Char;
begin
  { Create a file stream and open a text writer for it. }
  Reader := TStreamReader.Create(
    TFileStream.Create('local_file.txt', fmOpenRead),
    TEncoding.UTF8
  );

  mmText.Clear();

  { Check for the end of the stream and exit if necessary. }
  if Reader.EndOfStream then
  begin
    MessageDlg('Nothing to read!', mtInformation, [mbOK], 0);

    Reader.BaseStream.Free();
    Reader.Free();
  end;

  { Peek at each iteration to see whether there are characters
    to read from the reader. Peek is identical in its effect as
    EndOfStream property.
  }
  Line := '';

  while Reader.Peek() >= 0 do
  begin
    { Read the next character. }
    Ch := Char(Reader.Read());

    { Check for line termination (Unix-style). }
    if Ch = #$0A then
    begin
      mmText.Lines.Add(Line);
      Line := '';
    end
    else
      Line := Line + Ch;
  end;

  { Obtain the size of the data. }
  Size := Reader.BaseStream.Size;

  { Free the reader and underlying stream. }
  Reader.Close();
  Reader.BaseStream.Free;
  Reader.Free();

  MessageDlg(Format('%d bytes read from the stream using the %s encoding!',
    [Size, Reader.CurrentEncoding.ClassName]), mtInformation, [mbOK], 0);
end;

procedure TMainForm.btStoreClick(Sender: TObject);
var
  Writer: TStreamWriter;
  I, J: Integer;
  Size: Int64;
  Line: String;
begin
  { Create a file stream and open a text writer for it. }
  Writer := TStreamWriter.Create(
    TFileStream.Create('local_file.txt', fmCreate),
    TEncoding.UTF8
  );

  { Do not flush after each writing, it is done automatically. }
  Writer.AutoFlush := false;

  { Set the custom new-line to be Unix-compatible. }
  Writer.NewLine := #$0A;

  { Start storing all the lines in the memo. }
  for I := 0 to mmText.Lines.Count - 1 do
  begin
    { Obtain the line. }
    Line := mmText.Lines[I];

    { Write char-by-char. }
    for J := 1 to Length(Line) do
      Writer.Write(Line[J]);

    { Add a line terminator. }
    Writer.WriteLine();
  end;

  { Flush the contents of the writer to the stream. }
  Writer.Flush();

  { Close the writer. }
  Writer.Close();

  { Obtain the size of the data. }
  Size := Writer.BaseStream.Size;

  { Free the writer and underlying stream. }
  Writer.BaseStream.Free;
  Writer.Free();

  MessageDlg(Format('%d bytes written to the stream using the %s encoding!',
    [Size, Writer.Encoding.ClassName]), mtInformation, [mbOK], 0);
end;

Uses