2012-01-26 24 views
0

如何解压缩文件或读取zip文件的内容以选择要提取的内容?如何使用zlib充气和读取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 

回答

3

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

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

个人认为我发现rubyzip有点痛苦,所以我会倾向于考虑仅仅是对你已经使用的unzip命令进行脱壳。你可以做到这一点与

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

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

(或各种其他方式)

+0

啊,我没想到它是如此容易地运行在Ruby中的bash命令......我知道,拉链, gzip是不同的,但我很惊讶Ruby没有内置zip文件。 gzip可能会更好,但zip是如此普遍!感谢您的高举。 – beoliver

1

这里是你怎么会看一个ZIP文件的条目和可选阅读其内容。这个例子将打印从zip文件中README.txt项命名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