如何使用zlib充气和读取zip文件?

时间:2012-01-26 20:36:52

标签: ruby zlib unzip

如何解压缩文件或读取zip文件的内容以选择要提取的内容?

.pencast是压缩缩放的,因此我可以在bash中使用以下内容:

unzip -j *.pencast "*.aac"

但在Ruby中:

require 'zlib'

afile = "/Users/name/Desktop/Somepencast.pencast"
puts afile

def inflate(string)
  zstream = Zlib::Inflate.new
  buf = zstream.inflate(string)
  zstream.finish
  zstream.close
  buf
end

inflate(afile)

结果:

/Users/name/Desktop/Somepencast.pencast
prog1.rb:11:in `inflate': incorrect header check (Zlib::DataError)
  from prog1.rb:11:in `inflate'
  from prog1.rb:17

2 个答案:

答案 0 :(得分:3)

这可能会有所帮助:How do I get a zipped file's content using the rubyzip library?

zip和gzip是不同的协议,需要不同的解压缩软件。

我个人我发现rubyzip使用起来有点痛苦,所以我倾向于考虑刚刚使用你正在使用的解压缩命令。你可以用

做到这一点
`unzip -j *.pencast "*.aac"` # note backticks

system( 'unzip -j *.pencast "*.aac"' )

(或其他各种方式)

答案 1 :(得分:1)

以下是如何阅读ZIP文件的条目并可选择阅读其内容的方法。此示例将从名为README.txt的zip文件中打印foo.zip条目的内容:

require 'zip/zip'
zipfilename = 'foo.zip'
Zip::ZipFile.open(zipfilename) do |zipfile|
  zipfile.each do |entry|
    puts "ENTRY: #{entry.name}" # To see the entry name.
    if entry.name == 'README.txt'
      puts(entry.get_input_stream.read) # To read the contents.
    end
  end
end