将字符串和字节写入MemoryStream

时间:2013-01-30 20:20:34

标签: delphi

如何在Delphi中将'Hello World'字符串,clrf和一些随机10个字节写入内存流?

2 个答案:

答案 0 :(得分:6)

我会考虑使用二进制编写器来完成这项任务。这是一个更高级的类,负责处理将数据导入流中的细节。

var
  Stream: TMemoryStream;
  Writer: TBinaryWriter;
  Bytes: TBytes;
....
Stream := TMemoryStream.Create;
try
  Writer := TBinaryWriter.Create(Stream);
  try
    Writer.Write(TEncoding.UTF8.GetBytes('Hello World'+sLineBreak));
    //if you prefer, use a different encoding for your text
    Bytes := GetRandomBytes(10);//I assume you can write this
    Writer.Write(Bytes);
  finally
    Writer.Free;
  end;
finally
  Stream.Free;
end;

我希望你的真正问题比这更重要。使用编写器类的好处是,您可以将自己的数据流入流中。

答案 1 :(得分:4)

var
  ms: TMemoryStream;
  s: String;
  b: array[0..9] of Byte;
  i: Integer;
begin
  ms := TMemoryStream.Create;
  try
    s := 'Hello World' + #13#10;
    ms.Write(s[1], Length(s) * SizeOf(Char));
    for i := 0 to 9 do
      b[i] := Random(256);
    ms.Write(b[0], 10);
    // ms.SaveToFile('C:\temp\test.txt');

    {
    ms.Memory can be used for free access e.g.
    // build an empty buffer 5 characters
    s := '';
    SetLength(s,5);
    ms.Position := 5;
    // the position after which we want to copy
    i := Length('Hallo ')*SizeOf(Char);
    // copy bytes to string
    Move(TByteArray(ms.Memory^)[i],s[1],Length(s) * SizeOf(Char));
    Showmessage(s); // Display's "World"
    }


  finally
    ms.Free;
  end;    
end;