【问题标题】:How do I inflate and read zip files using zlib?如何使用 zlib 膨胀和读取 zip 文件?
【发布时间】:2012-01-26 20:36:52
【问题描述】:

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

.pencast 是 zip 压缩的,所以我可以在 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

【问题讨论】:

    标签: ruby zlib unzip


    【解决方案1】:

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

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

    个人我发现 ruby​​zip 使用起来有点痛苦,所以我倾向于考虑只使用你已经在使用的 unzip 命令。你可以这样做

    `unzip -j *.pencast "*.aac"` # note backticks
    

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

    (或其他各种方式)

    【讨论】:

    • 啊,我没有意识到在 Ruby 中运行 bash 命令这么容易......我知道 zip 和 gzip 是不同的,但我很惊讶 Ruby 没有 in - 专为拉链打造。 gzip 可能“更好”,但 zip 太常见了!感谢您的提醒。
    【解决方案2】:

    您可以通过以下方式读取 ZIP 文件的条目并选择性地读取其内容。此示例将打印名为 foo.zip 的 zip 文件中的 README.txt 条目的内容:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多