Reputation: 5759
How do you unzip a file, or read the contents of a zip file in order to select what to extract?
The .pencast
is zip compressed, so I can use the following in bash:
unzip -j *.pencast "*.aac"
But in 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)
results in:
/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
Upvotes: 0
Views: 4405
Reputation: 156434
Here is how you can read a ZIP file's entries and optionally read its contents. This example will print the contents of the README.txt
entry from the zip file named 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
Upvotes: 1
Reputation: 163
This might help: How do I get a zipped file's content using the rubyzip library?
zip and gzip are different protocols and need different unzipping software.
Personally I find rubyzip a bit of a pain to use, so I would be inclined to consider just shelling out to the unzip command you're already using. You can do that with
`unzip -j *.pencast "*.aac"` # note backticks
or
system( 'unzip -j *.pencast "*.aac"' )
(or various other ways)
Upvotes: 3