編輯:修改後的代碼,如果它存在事先刪除目標文件。
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