0

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
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
beoliver
  • 5,579
  • 5
  • 36
  • 72

2 Answers2

3

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)

Community
  • 1
  • 1
Ben Nagy
  • 163
  • 1
  • 6
  • Ah, I didn't realise it was so easy to run bash commands in Ruby... I'm aware that zip and gzip are different, but I'm surprised Ruby does not have an in-built for zip. gzip may be 'better' but zip is so common!. Thanks for the heads up. – beoliver Jan 27 '12 at 14:24
1

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
maerics
  • 151,642
  • 46
  • 269
  • 291