LoginSignup
0

More than 3 years have passed since last update.

Rubyでzipファイル作るならrubyzipだよね

Last updated at Posted at 2020-06-10

概要

とあるタスクで大量のzipファイルを作る必要があったのですが、このgemと出会ったことで救われました。
本記事ではrubyを使ってzipファイルを操作する4つの方法を紹介しています。

Rubyのバージョン

Ruby 2.4 またはそれ以上

gemをインストール

Gemfileに追加する

Gemfile
gem 'rubyzip'

ターミナルで次のコマンドを実行する

terminal
bundle install

4つの用途で使い分ける

1. zipファイルを作る

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

putsメソッドの引数には文字列またはファイルの読み込んだデータを使用してください。
生成されたzipファイルの中身は次の構造になります。

example.zip
- first_file.txt
- second_file.txt

またそれぞれのファイルの中身は以下のようになります。

first_file.txt
hoge hoge
second_file.txt
hoge again

2. zipファイルを読み取る

get_next_entryメソッドでzipファイル内のファイルが次々とセットされます。

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

1で生成されたexample.zipを読み取ると次のように表示されます。

terminal
First line of 'first_file.txt (10 bytes):  hoge hoge
First line of 'second_file.txt (11 bytes):  hoge again

3. zipファイルのディレクトリを読み取る

get_input_stream(entry)メソッドを使用して各エントリーのInputStreamを取得します。

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

このソースコードではzipファイル内に圧縮されたファイルのindex, name, size, conpressed_sizeを表示させます。

1で生成されたexample.zipを読み取ると次のように表示されます。

terminal
entry 0 is first_file.txt, size = 10, compressed size = 10
entry 1 is second_file.txt, size = 11, compressed size = 13

4. zipファイルを変更する

zipファイルを直接変更します

add(entry, path)でpathで示したファイルを追加
rename(entry, new_name)で名前を変更

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

以下のファイルを追加で用意しました。

third_file
hoge third
fourth_file
hogehoge fourth

実行してみます。
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

生成されたzipファイルは次の構造に変更されました。

example.zip
- second_file_txt
- third_file.txt
- first_file_rename.txt
- fourth_file.txt

まとめ

zipファイルを操作するための4つの方法を本記事で紹介しました。
rubyzipには他にも便利なメソッドが用意されているので一度見てみることをおすすめします。

参考

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
What you can do with signing up
0