StreamStrRdWr (Delphi)

From RAD Studio Code Examples
Jump to: navigation, search

Description

This example demonstrates the use of the TStreamReader and TStreamWriter classes. WriteLine and Write are used to store the text from the TMemo and the TEdit controls into the file, and ReadLine and ReadToEnd are used to load the stored contents.

Code

 { mmText :TMemo; }
 { edtTitle :TEdit; }
uses
  System.SysUtils, System.Classes;

procedure TMainForm.btLoadClick(Sender: TObject);
var
  Reader: TStreamReader;
begin
  { Create a new stream reader directly. }
  Reader := TStreamReader.Create( 'local_file.txt',
    TEncoding.UTF8);

  { Read the title and then the actual text. }
  edtTitle.Text := Reader.ReadLine();   
  mmText.Text := Reader.ReadToEnd();

  { Close and free the writer. }
  Reader.Free();
end;

procedure TMainForm.btSaveClick(Sender: TObject);
var
  Writer: TStreamWriter;
begin
  { Create a new stream writer directly. }
  Writer := TStreamWriter.Create('local_file.txt',
    false, TEncoding.UTF8);

  { Store the title and then the text. }
  Writer.WriteLine(edtTitle.Text);
  Writer.Write(mmText.Text);

  { Close and free the writer. }
  Writer.Free();
end;

Uses