【问题标题】:Ruby Unzip StringRuby 解压字符串
【发布时间】:2011-05-03 14:59:35
【问题描述】:

我必须使用 Ruby 中的压缩(常规 Zip)字符串。 显然我无法使用Ruby-ZipZip-Ruby 保存临时文件。

有没有可行的方法解压这个字符串?

【问题讨论】:

    标签: ruby zip


    【解决方案1】:

    rubyzipsupports StringIO since version 1.1.0

    require "zip"
    # zip is the string with the zipped contents
    Zip::InputStream.open(StringIO.new(zip)) do |io|
      while (entry = io.get_next_entry)
        puts "#{entry.name}: '#{io.read}'"
      end
    end
    

    【讨论】:

      【解决方案2】:

      Zip/Ruby Zip::Archive.open_buffer(...):

      require 'zipruby'
      Zip::Archive.open_buffer(str) do |archive|
        archive.each do |entry|
          entry.name
          entry.read
        end
      end
      

      【讨论】:

        【解决方案3】:

        由于 Ruby-Zip 似乎缺乏对 IO 对象的读/写支持,您可以伪造 File. 您可以执行以下操作:

        1. 在继承自 StringIO 的 Zip 模块下创建一个名为 File 的类,例如类 Zip::File
        2. 创建存在?类方法(返回真)
        3. 创建开放类方法(将 StringIO 提供给块)
        4. 存根关闭实例方法(如果需要)
        5. 也许它需要更多的假方法

        【讨论】:

        • 我会尽快检查的!
        • 探测方法当然是扩展 Ruby-Zip 库。
        【解决方案4】:

        正如@Roman 提到的,rubyzip 目前缺乏对 IO 对象的读写(包括StringIO.new(s))。尝试改用zipruby,如下所示:

        gem install zipruby
        
        require 'zipruby'
        
        # Given a string in zip format, return a hash where 
        # each key is an zip archive entry name and each
        # value is the un-zipped contents of the entry
        def unzip(zipfile)
          {}.tap do |h|
            Zip::Archive.open_buffer(zipfile) do |archive|
              archive.each {|entry| h[entry.name] = entry.read }
            end
          end
        end
        

        【讨论】:

          【解决方案5】:

          zlib 库。与 StringIO 一起工作正常。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2010-11-24
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-03-06
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多