gpt4 book ai didi

Delphi:从流中打开 zip 存档 -> 提取到流

转载 作者:行者123 更新时间:2023-12-03 14:49:37 27 4
gpt4 key购买 nike

是否有具有此类功能的 zip 组件?我需要从 Internet 将 zip 存档下载到流中,然后从流中打开存档,然后将文件提取到另一个流中。

例如ZipForge 可以从流中打开存档 ZipForge.OpenArchive(MyStream, false);但如何提取到另一个...?

procedure ExtractToStream(FileName: WideString; Stream: TStream); 

描述

Use ExtractToStream to decompress data stored in the file inside the archive to a TStream descendant object like TFileStream, TMemoryStream or TBlobStream.

The FileName parameter specifies file name being extracted.

如果不支持提取,OpenArchive(MyStream, false) 方法有什么用...

最佳答案

XE2 中内置的 zip 文件组件将执行此操作。

有一个重载的Open方法,它接收TStream作为其输入参数。

要提取单个文件,您可以调用重载的Read方法并传递您想要提取的文件的名称。提取的文件作为 TStream 的新实例返回。您可以在该实例上使用 CopyFrom 将提取的文件传输到您的流。

var
ZipFile: TZipFile;
DownloadedStream, DecompressionStream, MyStream: TStream;
LocalHeader: TZipHeader;
...
ZipFile := TZipFile.Create;
try
ZipFile.Open(DownloadedStream, zmRead);
ZipFile.Read('myzippedfile', DecompressionStream, LocalHeader);
try
MyStream.CopyFrom(DecompressionStream, DecompressionStream.Size);
finally
DecompressionStream.Free;
end;
finally
ZipFile.Free;
end;

请注意,我尚未测试此代码,我只是根据 TZipFile 的源代码以及该源代码中包含的文档编写了它。其中可能存在一些问题,但如果代码的行为如广告所示,它就可以完美满足您的需求。

<小时/>

好的,现在我测试一下,因为我很好奇。下面的程序表明这一切都如广告中所宣传的那样工作:

program ZipTest;

{$APPTYPE CONSOLE}

uses
System.SysUtils,
System.Classes,
System.Zip;

procedure ExtractToFile(
const ZipFileName: string;
const ZippedFileIndex: Integer;
const ExtractedFileName: string
);
var
ZipFile: TZipFile;
DownloadedStream, DecompressionStream, OutputStream: TStream;
LocalHeader: TZipHeader;
begin
DownloadedStream := TFileStream.Create(ZipFileName, fmOpenRead);
try
ZipFile := TZipFile.Create;
try
ZipFile.Open(DownloadedStream, zmRead);
ZipFile.Read(ZippedFileIndex, DecompressionStream, LocalHeader);
try
OutputStream := TFileStream.Create(ExtractedFileName, fmCreate);
try
OutputStream.CopyFrom(DecompressionStream, DecompressionStream.Size);
finally
OutputStream.Free;
end;
finally
DecompressionStream.Free;
end;
finally
ZipFile.Free;
end;
finally
DownloadedStream.Free;
end;
end;

begin
try
ExtractToFile('C:\desktop\test.zip', 0, 'C:\desktop\out.txt');
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
end.

请注意,我通过索引而不是文件名提取,因为这对我来说更方便。我使用文件流而不是我想你会使用的内存流。但是,由于 TZipFile 方法可与 TStream 配合使用,因此我确信该代码可与任何形式的流配合使用。

<小时/>

这是有关 ZIP 文件的一系列问题中的最新一个。我知道您正在使用 XE2,我想知道为什么您似乎不愿意使用 XE2 提供的内置 ZIP 类。我没有看到任何表明它不能满足您的要求的信息。事实上,正是这种直接使用流的能力让我觉得它对于任何应用程序都有足够的通用性。

关于Delphi:从流中打开 zip 存档 -> 提取到流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8891881/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com