LoginSignup
0
0

More than 1 year has passed since last update.

rubizipでzipファイル中のzipファイルにアクセスしてみた

Last updated at Posted at 2022-10-23

はじめに

rubyで、zipファイル中のzipファイルにアクセスする必要があり、いろいろ悩んでアクセスできたので、記録しておきます。
zipファイル中のzipのデータをioとして処理できずに悩みましたが、StringIOを使って解決することができました。

やりたい事例

  • hoge_hoge.zipの中にhoge.zipファイルがアーカイブされている。
  • hoge.zipの中にhoge1.txthoge2.txtがアーカイブされている。
  • hoge_hoge.zipからhoge1.txthoge2.txtにアクセスしたい。
hoge_hoge.zip
  +-- hoge.zip
      +-- hoge1.txt
      +-- hoge2.txt
hoge1.txt
hoge1 contents
hoge2.txt
hoge2 contents

コード

zip_in_zip.rb
require 'zip'

Zip::InputStream.open('hoge_hoge.zip') do |zio1|
  while (entry1 = zio1.get_next_entry)
    puts "entry1 file:  [#{entry1.name}]"
    if entry1.name == 'hoge.zip'
      sio = StringIO.new(zio1.read, 'r+')
      Zip::InputStream.open(sio) do |zio2|
        while (entry2 = zio2.get_next_entry)
          puts "+- entry2 file: [#{entry2.name}]"
          puts "   contents:    [#{zio2.readline.chomp}]"
        end
      end
    end
  end
end

実行結果

entry1 file:  [hoge.zip]
+- entry2 file: [hoge1.txt]
   contents:    [hoge1 contents]
+- entry2 file: [hoge2.txt]
   contents:    [hoge2 contents]
0
0
0

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
  3. You can use dark theme
What you can do with signing up
0
0