在Ruby中解压缩gzip文件时出现"not in gzip format (Zlib::GzipFile::Error)"错误

3
我正在尝试使用以下 Ruby 代码对文件进行解压缩。
File.open("file_compressed.gz") do |compressed|
  File.open("file_decomp","w") do |decompressed|
    gz = Zlib::GzipReader.new(compressed)
    result = gz.read
    decompressed.write(result)
    gz.close
  end
end

但是我遇到了以下错误 -
 not in gzip format (Zlib::GzipFile::Error)
 ./features/support/abc/abc_file.rb:44:in `initialize'

在Mac上使用gzip命令解压相同的文件时,我可以获得正确的未压缩输出。对于以下命令,我可以看到 -

 $file file_compressed.gz
 file_compressed.gz: gzip compressed data, from FAT filesystem (MS-DOS, OS/2, NT)

我需要在使用Zlib创建压缩文件时放置任何标题数据吗?因为当我使用inflate方法而不是GzipReader时,会出现以下错误 -
 incorrect header check (Zlib::DataError)
  ./features/support/abc/abc_file.rb:69:in `inflate'
1个回答

2

如果您使用的平台不使用LF分隔符,而是使用CR+LF,则可能需要以二进制模式打开文件进行读取:

File.open("file_compressed.gz", "rb") do |compressed|
  # ...
end

这样可以避免将输入流解释为除8位二进制以外的任何内容。

确保使用"wb"标志以相同的方式打开输出文件。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接