如何在 Delphi 中将“Hello World”字符串、clrf 和一些随机的 10 字节写入内存流?
user1593881
问问题
22865 次
2 回答
9
我会考虑使用二进制编写器来完成这项任务。这是一个更高级别的类,负责处理将数据导入流的细节。
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;
我希望您的真正问题比这更多。使用 writer 类的好处是您可以将自己与向流中喷射数据的血腥细节隔离开来。
于 2013-01-30T20:33:05.243 回答
5
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;
于 2013-01-30T20:27:04.663 回答