delphi 字符串与内存流和文件的快速转换函数
在delphi中没有能把字符串直接保存为文件的方法,也没有将文件直接作为字符串读出的方法。 没有能把字符串转化为内存流的方法,也没有能把内存流转化为字符串的方法。而这里有四个函数恰能做到。
代码如下:
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 }