编辑:修改后的代码,如果它存在事先删除目标文件。
require 'rubygems'
require 'fileutils'
require 'zip/zip'
def unzip_file(file, destination)
Zip::ZipFile.open(file) { |zip_file|
zip_file.each { |f|
f_path=File.join(destination, f.name)
if File.exist?(f_path) then
FileUtils.rm_rf f_path
end
FileUtils.mkdir_p(File.dirname(f_path))
zip_file.extract(f, f_path)
}
}
end
unzip_file('/path/to/file.zip', '/unzip/target/dir')
编辑:修改后的代码,以删除目标目录,如果它事先存在。
require 'rubygems'
require 'fileutils'
require 'zip/zip'
def unzip_file(file, destination)
if File.exist?(destination) then
FileUtils.rm_rf destination
end
Zip::ZipFile.open(file) { |zip_file|
zip_file.each { |f|
f_path=File.join(destination, f.name)
FileUtils.mkdir_p(File.dirname(f_path))
zip_file.extract(f, f_path)
}
}
end
unzip_file('/path/to/file.zip', '/unzip/target/dir')
这里的the original code from Mark Needham:
require 'rubygems'
require 'fileutils'
require 'zip/zip'
def unzip_file(file, destination)
Zip::ZipFile.open(file) { |zip_file|
zip_file.each { |f|
f_path=File.join(destination, f.name)
FileUtils.mkdir_p(File.dirname(f_path))
zip_file.extract(f, f_path) unless File.exist?(f_path)
}
}
end
unzip_file('/path/to/file.zip', '/unzip/target/dir')
感谢您的答案,但它看起来像不会覆盖现有的文件。如果它存在,它会跳过它。 – digitalsanctum 2009-06-08 19:37:17
...确实它跳过存在的文件。在发布之前,我多么愚蠢地没有测试该特定用例。我很抱歉。请参阅我的编辑版本,如果它预先存在,将删除目标目录。 – bernie 2009-06-08 19:56:16
而我的第二个解决方案也不理想。因为删除整个目录可能不太可取;但我相信第三次是一种魅力:我添加了一些代码来删除文件,如果它在写入新文件之前存在。 – bernie 2009-06-08 20:03:41