安装 rubyzip

通过提供的链接下载 “rubyzip” gem,并将它复制到系统中。在撰写本文之际,它的文件名是 “rubyzip-0.9.1.gem”)。
运行 gem 安装 rubyzip-0.9.1.gem


清单 3. 使用 zip 文件

 require 'rubygems'
require_gem 'rubyzip'
require 'find'
require 'zip/zip'
puts ""
puts "------------------File Search and Zip-----------------------------"
puts ""
print "Enter the search path    : "
searchpath = gets
searchpath = searchpath.chomp
puts ""
print "Enter the search pattern : "
pattern = gets
pattern = pattern.chomp
puts"----------------------------------------------------------------------"
puts "Searching in " + searchpath + " for files matching pattern " + pattern
puts"----------------------------------------------------------------------"
puts ""
puts"----------------------------------------------------------------------"
puts "Zipping up the found files..."
puts"----------------------------------------------------------------------"
Zip::ZipFile.open("test.zip", Zip::ZipFile::CREATE) {
|zipfile|
Find.find(searchpath) do |path|
if FileTest.directory?(path)
if File.basename(path)[0] == ?.
Find.prune       # Don't look any further into this directory.
else
next
end
else
if File.fnmatch(pattern,File.basename(path))
p File.basename(path)
zipfile.add(File.basename(path),path)
end
end
end
}

这个脚本为根据提供的搜索路径和搜索模式搜索到的文件创建一个名为 “test.zip” 的 zip 文件。

这个例子做以下事情:

第 9-15 行 - 请求用户提供搜索路径和搜索模式。
第 23 行 - 创建一个新的名为 “test.zip” 的 ZipFile。
第 25 行 - 使用 Ruby 中 “Find” 类中的 “find” 方法遍历指定的搜索路径。
第 26 行 - 检查发现的文件是否为一个目录。如果是目录,并且不是 “.”,则递归地遍历该目录。
第 33 行 - 使用 “File” 类中的 “fnmatch” 方法检查发现的文件是否符合给定的模式。
第 35 行 - 将符合的文件添加到 zip 归档中。
下面是一个示例输出:


清单 4. 第二个例子的示例输出


 [root@logan]# ruby zipexample.rb
-----------------------File Search-----------------------------------
Enter the search path    : /test
Enter the search pattern : *.rb
----------------------------------------------------------------------
Searching in /test for files matching pattern *.rb
----------------------------------------------------------------------
----------------------------------------------------------------------
Zipping up the found files...
----------------------------------------------------------------------
"s.rb"
"test.rb"
"s1.rb"
[root@logan]# unzip -l test.zip
Archive:  test.zip
Length     Date   Time    Name
--------    ----   ----    ----
996  09-25-08 21:01   test.rb
57  09-25-08 21:01   s.rb
39  09-25-08 21:01   s1.rb
--------                   -------
1092                   3 files


相关内容