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
我该如何解压缩字符串?
以上方法对我没用。
我一直收到incorrect header check (Zlib::DataError)
错误。 显然它默认假定您有一个头,但这并不总是正确的。
我的解决办法是:
require 'zlib'
require 'stringio'
gz = Zlib::GzipReader.new(StringIO.new(resp.body.to_s))
uncompressed_string = gz.read
def inflate(string)
zstream = Zlib::Inflate.new(-Zlib::MAX_WBITS)
buf = zstream.inflate(string)
zstream.finish
zstream.close
buf
end
在Rails中,您可以使用以下代码:
ActiveSupport::Gzip.compress("my string")
ActiveSupport::Gzip.decompress()
。 def inflate(string)
zstream = Zlib::Inflate.new
buf = zstream.inflate(string)
zstream.finish
zstream.close
buf
end
zstream = Zlib::Inflate.new(16+Zlib::MAX_WBITS)
使用(-Zlib::MAX_WBITS)
,我得到了ERROR: invalid code lengths set
和ERROR: invalid block type
的错误提示。
只有下面这个方法对我起作用。
Zlib::GzipReader.new(StringIO.new(response_body)).read
Zlib::GzipReader.new(StringIO.new(content), :external_encoding => content.encoding).read
注意编码问题
我使用上面的答案来使用Zlib::Deflate。
我一直得到损坏的文件(对于小文件),花费了很多时间才发现可以使用以下方法解决问题:
buf = zstream.deflate(string,Zlib::FINISH)
没有zstream.finish这行代码!
def self.deflate(string)
zstream = Zlib::Deflate.new
buf = zstream.deflate(string,Zlib::FINISH)
zstream.close
buf
end
现在我们不需要任何额外的参数。有deflate
和inflate
类方法,可以使用简短的一行代码:
>> data = "Hello, Zlib!"
>> compressed = Zlib::Deflate.deflate(data)
=> "x\234\363H\315\311\311\327Q\210\312\311LR\004\000\032\305\003\363"
>> uncompressed = Zlib::Inflate.inflate(compressed)
=> "Hello, Zlib!"