I had to create a lot of zip files for a certain task, but I was saved by encountering this gem. This article introduces four ways to work with zip files using ruby.
Ruby 2.4 or higher
Add to Gemfile
Gemfile
gem 'rubyzip'
Run the following command in the terminal
terminal
bundle install
Zip::OutputStream.open('example.zip') do |zos|
zos.put_next_entry('first_file.txt')
zos.puts 'hoge hoge'
zos.put_next_entry('second_file.txt')
zos.puts 'hoge again'
end
Use a string or the data read from the file as an argument to the puts
method.
The contents of the generated zip file have the following structure.
example.zip
- first_file.txt
- second_file.txt
The contents of each file are as follows.
first_file.txt
hoge hoge
second_file.txt
hoge again
The files in the zip file are set one after another by the get_next_entry
method.
Zip::InputStream.open('example.zip') do |zis|
entry = zis.get_next_entry
print "First line of '#{entry.name} (#{entry.size} bytes): "
puts "'#{zis.gets.chomp}'"
entry = zis.get_next_entry
print "First line of '#{entry.name} (#{entry.size} bytes): "
puts "'#{zis.gets.chomp}'"
end
If you read the ʻexample.zip` generated in ** 1 **, you will see the following.
terminal
First line of 'first_file.txt (10 bytes): hoge hoge
First line of 'second_file.txt (11 bytes): hoge again
Use the get_input_stream (entry)
method to get the ʻInputStream` for each entry.
zf = Zip::File.new('example.zip')
zf.each_with_index do |entry, index|
puts "entry #{index} is #{entry.name}, size = #{entry.size}, compressed size = #{entry.compressed_size}"
end
This source code displays the compressed files ʻindex,
name,
size,
compressed_size` in a zip file.
If you read the ʻexample.zip` generated in ** 1 **, you will see the following.
terminal
entry 0 is first_file.txt, size = 10, compressed size = 10
entry 1 is second_file.txt, size = 11, compressed size = 13
Modify the zip file directly
Add the file indicated by path with ʻadd (entry, path) Rename with
rename (entry, new_name)`
Modify the file generated by ** 1 **
Zip::File.open('example.zip') do |zip_file|
zip_file.add('third_file.txt', 'third_file.txt')
zip_file.rename('first_file.txt', 'first_file_rename.txt')
zip_file.add('fourth_file.txt', 'fourth_file.txt')
end
The following files are additionally prepared.
third_file
hoge third
fourth_file
hogehoge fourth
I will try it. Get information using ** 3 **
terminal
entry 0 is second_file.txt, size = 11, compressed size = 13
entry 1 is third_file.txt, size = 10, compressed size = 12
entry 2 is first_file_rename.txt, size = 10, compressed size = 10
entry 3 is fourth_file.txt, size = 14, compressed size = 14
The generated zip file has been modified to have the following structure:
example.zip
- second_file_txt
- third_file.txt
- first_file_rename.txt
- fourth_file.txt
In this article, I have introduced four ways to work with zip files.
There are other useful methods in rubyzip
, so it is recommended to take a look.
https://github.com/rubyzip/rubyzip
Recommended Posts