如何在 ruby 中解压缩 Gzip 字符串?
Zlib::GzipReader 可以采用“IO 或类似 IO 的对象”。正如文档中所述,它是输入的。
Zlib::GzipReader.open('hoge.gz') {|gz|
print gz.read
}
File.open('hoge.gz') do |f|
gz = Zlib::GzipReader.new(f)
print gz.read
gz.close
end
我应该如何解压缩字符串?
Zlib::GzipReader can take "an IO, or IO-like, object." as it's input, as stated in docs.
Zlib::GzipReader.open('hoge.gz') {|gz|
print gz.read
}
File.open('hoge.gz') do |f|
gz = Zlib::GzipReader.new(f)
print gz.read
gz.close
end
How should I ungzip a string?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
上述方法对我来说不起作用。
我不断收到
不正确的标头检查(Zlib::DataError)
错误。显然,它假设您默认有一个标头,但情况可能并非总是如此。我实施的解决方法是:
The above method didn't work for me.
I kept getting
incorrect header check (Zlib::DataError)
error. Apparently it assumes you have a header by default, which may not always be the case.The work around that I implemented was:
默认情况下,Zlib 假定您的压缩数据包含标头。
如果您的数据不包含标头,它将因引发 Zlib::DataError 而失败。
您可以通过以下解决方法告诉 Zlib 假设数据没有标头:
Zlib by default asumes that your compressed data contains a header.
If your data does NOT contain a header it will fail by raising a Zlib::DataError.
You can tell Zlib to assume the data has no header via the following workaround:
在 Rails 中,您可以使用:
ActiveSupport::Gzip.compress("my string")
ActiveSupport::Gzip.decompress()
。In Rails you can use:
ActiveSupport::Gzip.compress("my string")
ActiveSupport::Gzip.decompress()
.您需要 Zlib::Inflate 来解压缩字符串和 Zlib::Deflate 用于压缩
You need Zlib::Inflate for decompression of a string and Zlib::Deflate for compression
zstream = Zlib::Inflate.new(16+Zlib::MAX_WBITS)
zstream = Zlib::Inflate.new(16+Zlib::MAX_WBITS)
使用
(-Zlib::MAX_WBITS)
,我得到错误:无效的代码长度设置
和错误:无效的块类型
以下唯一的内容也适用于我。
Using
(-Zlib::MAX_WBITS)
, I gotERROR: invalid code lengths set
andERROR: invalid block type
The only following works for me, too.
我使用上面的答案来使用 Zlib::Deflate
我不断收到损坏的文件(对于小文件),并且花了很多小时才发现可以使用以下方法修复问题:
没有 zstream.finish 行!
I used the answer above to use a Zlib::Deflate
I kept getting broken files (for small files) and it took many hours to figure out that the problem can be fixed using:
without the the zstream.finish line!
要gunzip内容,请使用以下代码(在1.9.2上测试)
注意编码问题
To gunzip content, use following code (tested on 1.9.2)
Beware of encoding problems
现在我们不需要任何额外的参数。有
deflate
和inflate
类方法允许像这样的快速单行代码:我认为它回答了“我应该如何解压缩字符串?”的问题。最好的。 :)
We don't need any extra parameters these days. There are
deflate
andinflate
class methods which allow for quick oneliners like these:I think it answers the question "How should I ungzip a string?" the best. :)