delphi 怎么将一个流转换成字符串?

//from   
http://kingron.myetang.com/zsfunc0d.htm   

(*//   
标题:充分利用pascal字符串类型   
说明:和PChar不同,string可以保存#0字符在其中;示例文件、内存流字符串之间转换   
设计:Zswang   
日期:2002-01-25   
支持:wjhu111@21cn.com   
//*)   

///Begin   Source   
function   StringToFile(mString:   string;   mFileName:   TFileName):   Boolean;   
{   返回字符串保存到文件是否成功   }   
var   
vFileChar:   file   of   Char;   
I:   Integer;   
begin   
{$I-}   
AssignFile(vFileChar,   mFileName);   
Rewrite(vFileChar);   
for   I   :=   1   to   Length(mString)   do   Write(vFileChar,   mString[I]);   
CloseFile(vFileChar);   
{$I+}   
Result   :=   (IOResult   =   0)   and   (mFileName   <>   '');   
end;   {   StringToFile   }   

function   FileToString(mFileName:   TFileName):   string;   
{   返回从文件载入字符串   }   
var   
vFileChar:   file   of   Char;   
vChar:   Char;   
begin   
Result   :=   '';   
{$I-}   
AssignFile(vFileChar,   mFileName);   
Reset(vFileChar);   

while   not   Eof(vFileChar)   do   begin   
Read(vFileChar,   vChar);   
Result   :=   Result   +   vChar;   
end;   
CloseFile(vFileChar);   
{$I+}   
end;   {   FileToString   }   

function   StreamToString(mStream:   TStream):   string;   
{   将内存流转换成字符串   }   
var   
I:   Integer;   
begin   
Result   :=   '';   
if   not   Assigned(mStream)   then   Exit;   
SetLength(Result,   mStream.Size);   
for   I   :=   0   to   Pred(mStream.Size)   do   try   
mStream.Position   :=   I;   
mStream.Read(Result[Succ(I)],   1);   
except   
Result   :=   '';   
end;   
end;   {   StreamToString   }   

function   StringToStream(mString:   string;   mStream:   TStream):   Boolean;   
{   返回将字符串保存到内存流是否成功   }   
var   
I:   Integer;   
begin   
Result   :=   True;   
try   
mStream.Size   :=   0;   
mStream.Position   :=   0;   
for   I   :=   1   to   Length(mString)   do   mStream.Write(mString[I],   1);   
except   
Result   :=   False;   
end;   
end;   {   StringToStream   }   
///End   Source   

///Begin   Demo   
procedure   TForm1.Button1Click(Sender:   TObject);   
var   
vMemoryStream:   TMemoryStream;   
begin   
Memo1.Text   :=   FileToString('C:\WINDOWS\Desktop\1.txt');   
vMemoryStream   :=   TMemoryStream.Create;   
try   
Memo1.Lines.SaveToStream(vMemoryStream);   
Memo2.Text   :=   StreamToString(vMemoryStream);   
finally   
vMemoryStream.Free;   
end;   
end;   

procedure   TForm1.Button2Click(Sender:   TObject);   
var   
vMemoryStream:   TMemoryStream;   
begin   
StringToFile(Memo2.Text,   'C:\WINDOWS\Desktop\1.txt');   
vMemoryStream   :=   TMemoryStream.Create;   
try   
StringToStream(Memo2.Text,   vMemoryStream);   
vMemoryStream.Position   :=   0;   
Memo1.Lines.LoadFromStream(vMemoryStream);   
finally   
vMemoryStream.Free;   
end;   
end;   
///End   Demo  


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值