|
| 1 | +# Taken from https://github.com/rubyzip/rubyzip/blob/v3.2.0/samples/example.rb |
| 2 | + |
| 3 | +require 'zip' |
| 4 | + |
| 5 | +####### Using ZipInputStream alone: ####### |
| 6 | + |
| 7 | +Zip::InputStream.open('example.zip') do |zis| |
| 8 | + entry = zis.get_next_entry |
| 9 | + print "First line of '#{entry&.name} (#{entry&.size} bytes): " |
| 10 | + puts "'#{zis.gets&.chomp}'" |
| 11 | + entry = zis.get_next_entry |
| 12 | + print "First line of '#{entry&.name} (#{entry&.size} bytes): " |
| 13 | + puts "'#{zis.gets&.chomp}'" |
| 14 | +end |
| 15 | + |
| 16 | +####### Using ZipFile to read the directory of a zip file: ####### |
| 17 | + |
| 18 | +zf = Zip::File.new('example.zip') |
| 19 | +zf.each_with_index do |entry, index| |
| 20 | + puts "entry #{index} is #{entry.name}, size = #{entry.size}, compressed size = #{entry.compressed_size}" |
| 21 | + # use zf.get_input_stream(entry) to get a ZipInputStream for the entry |
| 22 | + # entry can be the ZipEntry object or any object which has a to_s method that |
| 23 | + # returns the name of the entry. |
| 24 | +end |
| 25 | + |
| 26 | +####### Using ZipOutputStream to write a zip file: ####### |
| 27 | + |
| 28 | +Zip::OutputStream.open('exampleout.zip') do |zos| |
| 29 | + zos.put_next_entry('the first little entry') |
| 30 | + zos.puts 'Hello hello hello hello hello hello hello hello hello' |
| 31 | + |
| 32 | + zos.put_next_entry('the second little entry') |
| 33 | + zos.puts 'Hello again' |
| 34 | + |
| 35 | + # Use rubyzip or your zip client of choice to verify |
| 36 | + # the contents of exampleout.zip |
| 37 | +end |
| 38 | + |
| 39 | +####### Using ZipFile to change a zip file: ####### |
| 40 | + |
| 41 | +Zip::File.open('exampleout.zip') do |zip_file| |
| 42 | + zip_file.add('thisFile.rb', 'example.rb') |
| 43 | + zip_file.rename('thisFile.rb', 'ILikeThisName.rb') |
| 44 | + zip_file.add('Again', 'example.rb') |
| 45 | +end |
| 46 | + |
| 47 | +# Lets check |
| 48 | +Zip::File.open('exampleout.zip') do |zip_file| |
| 49 | + puts "Changed zip file contains: #{zip_file.entries.join(', ')}" |
| 50 | + zip_file.remove('Again') |
| 51 | + puts "Without 'Again': #{zip_file.entries.join(', ')}" |
| 52 | +end |
| 53 | + |
| 54 | +####### Using ZipFile to split a zip file: ####### |
| 55 | + |
| 56 | +# Creating large zip file for splitting |
| 57 | +Zip::OutputStream.open('large_zip_file.zip') do |zos| |
| 58 | + puts 'Creating zip file...' |
| 59 | + 10.times do |i| |
| 60 | + zos.put_next_entry("large_entry_#{i}.txt") |
| 61 | + zos.puts 'Hello' * 104_857_600 |
| 62 | + end |
| 63 | +end |
| 64 | + |
| 65 | +# Splitting created large zip file |
| 66 | +part_zips_count = Zip::File.split('large_zip_file.zip', segment_size: 2_097_152, delete_original: false, partial_zip_file_name: 'part_zip_file') |
| 67 | +puts "Zip file splitted in #{part_zips_count} parts" |
0 commit comments