Reading files in a zip archive, without unzipping the archive

I came across the same issue and checking for if entry.file?, before entry.get_input_stream.read, resolved the issue.

require 'zip'

Zip::File.open('my_zip.zip') do |zip_file|
  # Handle entries one by one
  zip_file.each do |entry|
    # Extract to file/directory/symlink
    puts "Extracting #{entry.name}"
    entry.extract('here')

    # Read into memory
    if entry.file?
      content = entry.get_input_stream.read
    end
  end
end 

The Zip::NullInputStream is returned if the entry is a directory and not a file, could that be the case?

Here's a more robust variation of the code:

#!/usr/bin/env ruby

require 'rubygems'
require 'zip'


Zip::File.open('my_zip.zip') do |zip_file|
  # Handle entries one by one
  zip_file.each do |entry|
    if entry.directory?
      puts "#{entry.name} is a folder!"
    elsif entry.symlink?
      puts "#{entry.name} is a symlink!"
    elsif entry.file?
      puts "#{entry.name} is a regular file!"

      # Read into memory
      entry.get_input_stream { |io| content = io.read }

      # Output
      puts content
    else
      puts "#{entry.name} is something unknown, oops!"
    end
  end
end

Tags:

Ruby