tags:

views:

29

answers:

1

I would like to use rubyzip to archive "zip" an existing file:

c:\textfile.txt

to

textfile.zip

I know how to add a stream to a text file:

require 'zip/zip'

 Zip::ZipFile.open("mp.zip", Zip::ZipFile::CREATE) {
   |zipfile|
    zipfile.get_output_stream("text.txt") { |f| f.puts "Creating text file" }
    }

but not how to add an existing file to a zip. Thanks for your help

A: 

This reads in the source file and writes it 1mb at a time to the zipfile.

I've been using something very similar in production for some time now.

require 'zip/zip'

Zip::ZipFile.open("mp.zip", Zip::ZipFile::CREATE) do |zipfile|
    zipfile.get_output_stream("text.txt") do |out_file|
      File.open("text.txt") do |in_file|
        while blk = in_file.read(1024**2)
          out_file << blk
        end
      end
    end
end

Hope this answers your question.

cwninja