10 - reading and writing zip files.rb

来自「O Reilly Ruby Cookbook source code」· RB 代码 · 共 37 行

RB
37
字号
require 'rubygems'require 'zip/zipfilesystem'Zip::ZipFile.open('zipfile.zip', Zip::ZipFile::CREATE) do |zip|  zip.file.open('file1', 'w') { |f1| f1 << 'This is file 1.' }  zip.dir.mkdir('subdirectory')  zip.file.open('subdirectory/file2', 'w') { |f1| f1 << 'This is file 2.' }end#---def process_zipfile(zip, path='')  if zip.file.file? path    puts %{#{path}: "#{zip.read(path)}"}  else    unless path.empty?      path += '/'      puts path    end    zip.dir.foreach(path) do |filename|      process_zipfile(zip, path + filename)    end  endend#---Zip::ZipFile.open('zipfile.zip') do |zip|  process_zipfile(zip)end# subdirectory/# subdirectory/file2: "This is file 2."# file1: "This is file 1."#---Zip::ZipFile.open('zipfile2.zip', Zip::ZipFile::CREATE) do |zip|  zip.get_output_stream('file1') { |f| f << 'This is file 1.' }  zip.mkdir('subdirectory')  zip.get_output_stream('subdirectory/file2') { |f| f << 'This is file 2.' }end#---

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?