简体   繁体   English

将字符串和字节写入MemoryStream

[英]Writing strings and bytes to a MemoryStream

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

I would consider using a binary writer for this task. 我会考虑使用二进制编写器来完成这项任务。 This is a higher level class that takes care of the details of getting data into the stream. 这是一个更高级别的类,负责处理将数据导入流中的详细信息。

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;

I expect that your real problem is more involved than this. 我希望你的真正问题比这更重要。 The benefit of using the writer class is that you insulate yourself from the gory details of spewing data to the stream. 使用编写器类的好处是,您可以将自己的数据流入流中。

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM