我正在使用 Delphi XE 8 并尝试解压缩 gzip 文件。 我直接从 Embarcadero 网站复制了以下代码作为示例,但我收到“EZDecompressionError,并显示消息“数据错误”。
procedure DecompressGzip(inFileName : string);
var
LInput, LOutput: TFileStream;
LUnZip: TZDecompressionStream;
begin
{ Create the Input, Output, and Decompressed streams. }
LInput := TFileStream.Create(InFileName, fmOpenRead);
LOutput := TFileStream.Create(ChangeFileExt(InFileName, 'txt'), fmCreate);
LUnZip := TZDecompressionStream.Create(LInput);
{ Decompress data. }
LOutput.CopyFrom(LUnZip, 0);
{ Free the streams. }
LUnZip.Free;
LInput.Free;
LOutput.Free;
end;
我尝试解压缩的示例文件位于此处: http://ftp.nhc.noaa.gov/atcf/aid_public/
最佳答案
您的代码是正确的,但您忘记启用 zlib
来检测 gzip
header (默认情况下,唯一识别的数据格式是 zlib 格式)。您必须调用 TDecompressionStream.Create(source: TStream; WindowBits: Integer)
重载构造函数,并指定 zlib
应在流中查找 gzip
的深度标题:
procedure TForm2.FormCreate(Sender: TObject);
var
FileStream: TFileStream;
DecompressionStream: TDecompressionStream;
Strings: TStringList;
begin
FileStream := TFileStream.Create('aal012015.dat.gz', fmOpenRead);
{
windowBits can also be greater than 15 for optional gzip decoding. Add
32 to windowBits to enable zlib and gzip decoding with automatic header
detection, or add 16 to decode only the gzip format (the zlib format will
return a Z_DATA_ERROR).
}
DecompressionStream := TDecompressionStream.Create(FileStream, 15 + 16); // 31 bit wide window = gzip only mode
Strings := TStringList.Create;
Strings.LoadFromStream(DecompressionStream);
ShowMessage(Strings[0]);
{ .... }
end;
如需进一步引用,请查看zlib
manual ,还有 this question可能有用。
关于Delphi XE 8 - 如何解压缩 gzip 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31221429/