题
我试图解压缩文件与可能或可能不会已经在目标目录中存在多个文件。这似乎默认行为是,如果该文件已经存在抛出异常。
我如何解压到一个目录,并简单地覆盖现有文件?
下面是我的代码:
begin
Zip::ZipFile.open(source) do |zipfile|
dir = zipfile.dir
dir.entries('.').each do |entry|
zipfile.extract(entry, "#{target}/#{entry}")
end
end
rescue Exception => e
log_error("Error unzipping file: #{local_zip} #{e.to_s}")
end
解决方案
看起来提取物()接受一个可选的块(onExistsProc),它允许你以确定哪些与文件进行操作,如果它已经存在 - 返回true覆盖,假引发异常
如果你想简单地覆盖所有现有文件,你可以这样做:
zipfile.extract(entry, "#{target}/#{entry}") { true }
如果你想要做一些更复杂的逻辑,以不同的方式处理特定条目,你可以这样做:
zipfile.extract(entry, "#{target}/#{entry}") {|entry, path| some_logic(entry, path) }
修改:强>固定答案 - 如由英格玛哈默指出,我原来的答复传递的块作为一个参数时,它的使用上述的语法预期
其他提示
只是为了拯救他人的麻烦:
在回答2萃取命令是不正确:
在第三(PROC)参数wtih一个符号指定,这意味着红宝石希望它是在{} -Brackets这样的方法调用后:
zipfile.extract(entry, "#{target}/#{entry}"){ true }
或(如果需要更复杂的逻辑)
zipfile.extract(entry, "#{target}/#{entry}") {|entry, path| some_logic(entry, path) }
如果您在帖子#给出的例子2,你会得到一个“无效的参数(3 2)”的错误...
编辑:修改后的代码,如果它预先存在删除目标文件
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')
下面的原码从马克·尼德姆:
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')
此链路提供了我已经验证工作一个很好的例子。仅需要有一个需要“文件实用程序”添加到它。
不隶属于 StackOverflow