如何使用MemoryStream
将Tbytes
类型转换为Binary file
?
或者直接使用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
在这里没有帮助,因为它只涉及额外的不必要的堆分配/释放。
如果您有可用的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;
好吧,如果答案提到Delphi XE和TMemoryStream
之外的其他流,那么我建议再使用一种方法。
procedure SaveBytesToFile(const Data: TBytes; const FileName: string);
begin
TFile.WriteAllBytes( FileName, Data );
end;
Delphi XE:中的F.I
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;