StringReadWrite (Delphi)

From RAD Studio Code Examples
Jump to: navigation, search

Description

This example demonstrates the use of the TStringReader and TStringWriter classes.

Code

procedure TMainForm.btReadClick(Sender: TObject);
var
  Reader1, Reader2: TStringReader;
  Ch: Char;
  Line: String;
  Buffer: TCharArray;
begin
  { Create a string reader }
  Reader1 := TStringReader.Create('This is the first text' + sLineBreak +
     'This is the first line' + sLineBreak + 'This is the second line');
  Reader2 := TStringReader.Create('This is the second text' + sLineBreak +
     'This is the first line' + sLineBreak + 'This is the second line');

  { Read the first string }
  Edit1.Text := Reader1.ReadLine;
  Memo1.Text := Reader1.ReadToEnd;
  { Prepare a buffer }
  SetLength(Buffer,25);

  { Read first 25 characters from the second string }
  if Reader2.ReadBlock(Buffer,0,Length(Buffer)) < Length(Buffer) then
    MessageDlg('Reading failed! Expected to read 25 characters!',
      mtError, [mbOK], 0);

  { Read the rest of the second string, char by char and write it in the
    second memo box }
  Line := '';
  while Reader2.Peek() >= 0 do
    begin
      Ch := Char(Reader2.Read());
      Line := Line + Ch;
  end;
  Memo2.Text := Line;

  { Close the reader }
  Reader1.Close;
  Reader2.Close;
end;

procedure TMainForm.btWriteClick(Sender: TObject);
var
  Writer: TStringWriter;
  MyStr: String;

begin
  { Create a string writer }
  Writer := TStringWriter.Create;

  { Store the text in the writer }
  Writer.WriteLine(Edit1.Text);
  Writer.Write(Memo1.Text + sLineBreak + Memo2.Text);
  MyStr := Writer.ToString;
  ShowMessage(MyStr);

  { Clear writer's buffer data }
  Writer.Flush();

  { Close the writer }
  Writer.Close;
  Writer.Destroy;
end;

Uses