注意:TStream 是一个抽象的基类, 不能直接生成对象. 在具体的应用中, 主要使用它的子孙类:
TFileStream: 文件流
TStringStream: 字符串流
TMemoryStream: 内存流
TResourceStream: 资源文件流
THandleStream: 是 TFileStream 的父类、TStream 的子类
TCustomMemoryStream: 是 TMemoryStream 和 TResourceStream 的父类、TStream 的子类
与流相关的常用类还有: TReader、TWriter、TCompressionStream、TDecompressionStream
下面的例子应用了TFileStream
源代码:
-------------------------------------------------------------------------
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, StdCtrls;
type
TForm1 = class(TForm)
Image1: TImage;
Button1: TButton;
Button2: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
fStream1,fStream2:TStream;
//注意先使用流的基类,然后再后面的代码中用子类创建实例
implementation
{$R *.dfm}
{$APPTYPE CONSOLE}
procedure TForm1.Button1Click(Sender: TObject);
var
fname1,fname2:string;
begin
fname1:=ExtractFilePath(Application.ExeName)+'logo.bmp';
fStream1:=TFileStream.Create(fname1,fmOpenRead or fmShareExclusive); //只读打开
fname2:=ExtractFilePath(Application.ExeName)+'mid.bmp';
fStream2:=TFileStream.Create(fname2,fmCreate);
fStream1.Position:=0;
fStream2.CopyFrom(fStream1,fStream1.Size);
//上面的操作其实就是用流读出logo.bmp的数据,然后再拷贝给另一个流fStream2
//Image1.Picture.LoadFromFile('c:\logo1.bmp');
//注意上面这句是不能写在fStream2.CopyFrom后面,会出现错误
//“另一个进程正在访问logo1.bmp文件”,因为可能是因为流操作是异步的
//所以我把这步操作写到了另一个按钮“载入”的事件中去了。
fStream1.Free;
fStream2.Free;
end;
procedure TForm1.Button2Click(Sender: TObject);
var
picPath:string;
begin
picPath:=ExtractFilePath(Application.ExeName)+'mid.bmp';
if FileExists(picPath) then
Image1.Picture.LoadFromFile(picPath);
end;
end.