随笔 - 2146  文章 - 97 评论 - 11767 trackbacks - 253


TStreamWriter 和 TStringWriter 都是继承于抽象类: TTextWriter;
TStreamReader 和 TStringReader 都是继承于抽象类: TTextReader.

它们的功能相似, 不过 TStreamWriter、TStreamReader 又有了 "流" 的特性, 比较适合对字符串流的读写.

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    Button2: TButton;
    Button3: TButton;
    Button4: TButton;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
    procedure Button3Click(Sender: TObject);
    procedure Button4Click(Sender: TObject);
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

const FilePath = 'c:\temp\test.txt';

//貌似是流操作, 其实写入的非字符串类型也都转换成了字符串
procedure TForm1.Button1Click(Sender: TObject);
var
  Writer: TStreamWriter;
  Reader: TStreamReader;
begin
  Writer := TStreamWriter.Create(FilePath);
  Writer.WriteLine('string');
  Writer.WriteLine(123);
  Writer.WriteLine(True);
  Writer.WriteLine(3.14);
  Writer.Close;
  Writer.Free;

  Reader := TStreamReader.Create(FilePath);
  ShowMessage(Reader.ReadToEnd);
  Reader.Close;
  Reader.Free;
end;

//读写时可指定字符编码
procedure TForm1.Button2Click(Sender: TObject);
var
  Writer: TStreamWriter;
  Reader: TStreamReader;
begin
  {参数 2 如果是 True 将会在已有文件的后面添加; False 是新建文件}
  Writer := TStreamWriter.Create(FilePath, False, TEncoding.Unicode);
  Writer.WriteLine('万一的 Delphi 博客');
  Writer.Close;
  Writer.Free;

  Reader := TStreamReader.Create(FilePath, Tencoding.Unicode);
  ShowMessage(Reader.ReadToEnd);
  Reader.Close;
  Reader.Free;
end;

//不指定编码时, 默认的是 UTF8
procedure TForm1.Button3Click(Sender: TObject);
var
  Writer: TStreamWriter;
  Reader: TStreamReader;
begin
  Writer := TStreamWriter.Create(FilePath);
  Writer.Write('万一的 Delphi 博客');
  Writer.Close;
  Writer.Free;

  Reader := TStreamReader.Create(FilePath);
  ShowMessage(Reader.CurrentEncoding.ClassName); {TUTF8Encoding}
  Reader.EndOfStream;
  Reader.Close;
  Reader.Free;
end;

//可基于另一个 TStream 创建; 从 BaseStream 上看它的确就是个流
procedure TForm1.Button4Click(Sender: TObject);
var
  Writer: TStreamWriter;
  Reader: TStreamReader;
begin
  Writer := TStreamWriter.Create(TFileStream.Create(FilePath, fmCreate), TEncoding.UTF8);
  Writer.Write('万一的 Delphi 博客');
  Writer.BaseStream.Free;
  Writer.Close;
  Writer.Free;

  Reader := TStreamReader.Create(TFileStream.Create(FilePath, fmOpenRead), TEncoding.UTF8);
  ShowMessage(Reader.ReadLine); {万一的 Delphi 博客}
  Reader.BaseStream.Free;
  Reader.Close;
  Reader.Free;
end;

end.

posted on 2009-10-12 20:05  万一  阅读(...)  评论(...编辑  收藏