delphi – 将字符串写入TMemoryStream

前端之家收集整理的这篇文章主要介绍了delphi – 将字符串写入TMemoryStream前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在这里已经阅读了很多关于将字符串写入TMemoryStream并保存到文件并将字符串读回TMemoryStream的讨论

我不知道我在这里做错了什么,但我的SaveData或我的LoadData都是错误的.我可以在调用SaveData之前检查Title的值,它符合我的预期.但是,当我调用LoadData并检查Title的值时,它是垃圾.任何人都可以告诉我,我做错了

procedure SaveData(FileName: TFileName);
var
 MemStr: TMemoryStream;
 Title: String;
begin
 MemStr:= TMemoryStream.Create;
try
 MemStr.Seek(0,soFromBeginning);
 WriteStreamStr( MemStr,TItle );
 MemStr.SaveToFile(FileName);
finally
 MemStr.Free;
end;
end;

procedure LoadData(FileName: TFileName);
var
 MemStr: TMemoryStream;
 Title: String;
begin
 MemStr:= TMemoryStream.Create;
 try
  MemStr.LoadFromFile(FileName);
  MemStr.Seek(0,soFromBeginning);
  Title := ReadStreamStr( MemStr );
 finally
   MemStr.Free;
  end;
end;



procedure WriteStreamInt(Stream : TStream; Num : integer);
 {writes an integer to the stream}
begin
 Stream.WriteBuffer(Num,SizeOf(Integer));
end;

procedure WriteStreamStr(Stream : TStream; Str : string);
 {writes a string to the stream}
var
 StrLen : integer;
begin
 {get length of string}
 StrLen := Length(Str);
 {write length of string}
 WriteStreamInt(Stream,StrLen);
 if StrLen > 0 then
 {write characters}
 Stream.Write(Str[1],StrLen);
end;


function ReadStreamInt(Stream : TStream) : integer;
 {returns an integer from stream}
begin
 Stream.ReadBuffer(Result,SizeOf(Integer));
end;

function ReadStreamStr(Stream : TStream) : string;
 {returns a string from the stream}
var
 LenStr : integer;
begin
 Result := '';
 {get length of string}
 LenStr := ReadStreamInt(Stream);
 {set string to get memory}
 SetLength(Result,LenStr);
 {read characters}
 Stream.Read(Result[1],LenStr);
end;

解决方法

当你使用
Stream.Write(Str[1],StrLen);

您正在将第一个StrLen字节写入流中.但是(unicode)字符串数据实际上是StrLen * SizeOf(Char)字节(您必须考虑char类型的大小).以下应该工作:

Stream.Write(Str[1],StrLen * SizeOf(Str[1]));

从流中读取数据时相同.

猜你在找的Delphi相关文章