如何使用Tbytes
将Binary file
类型转换为MemoryStream
?
答案 0 :(得分:27)
或直接使用TFileStream
来减少创建的中间对象的数量:
procedure SaveBytesToFile(const Data: TBytes; const FileName: string);
var
Stream: TFileStream;
begin
Stream := TFileStream.Create(FileName, fmCreate);
try
if Data <> nil then
Stream.WriteBuffer(Data[0], Length(Data));
finally
Stream.Free;
end;
end;
我不相信使用TMemoryStream
在这里有用,因为它只涉及额外的不必要的堆分配/释放。
答案 1 :(得分:11)
如果您有TBytesStream,Uwe的答案将会有效。如果不是:
procedure SaveBytesToFile(const Data: TBytes; const FileName: string);
var
stream: TMemoryStream;
begin
stream := TMemoryStream.Create;
try
if length(data) > 0 then
stream.WriteBuffer(data[0], length(data));
stream.SaveToFile(FileName);
finally
stream.Free;
end;
end;
答案 2 :(得分:6)
F.I。在Delphi XE中:
procedure SaveBytesToFile(const Data: TBytes; const FileName: string);
var
stream: TBytesStream;
begin
stream := TBytesStream.Create(Data);
try
stream.SaveToFile(FileName);
finally
stream.Free;
end;
end;
答案 3 :(得分:5)
好吧,如果答案提到Delphi XE和除TMemoryStream
以外的其他流,那么我建议再采用一种方法。
procedure SaveBytesToFile(const Data: TBytes; const FileName: string);
begin
TFile.WriteAllBytes( FileName, Data );
end;