我正在尝试重命名zip中的文件和目录。我试过三种不同的,都不起作用。什么是正确的命令?
以下是我的代码摘录:
require 'zip/zip'
...
def renaming_zip(zip_file)
Zip::ZipFile.open(zip_file).each do |entry|
if entry.name == "mimetype"
puts "#{entry.name} is a file ? #{File.file? entry.name}"
puts " class ? #{entry.class}"
new_filename = "#{entry.name.gsub("mimetype", "#mimetype-new")}"
#found_entry = entry.get_entry("mimetype")
#found_entry.name = new_filename #1st try
puts " new filename #{new_filename}"
#File.rename(entry.name, new_filename) #2nd try
#entry.rename(entry.name, new_filename) #3rd try
end
end
end
如果我在没有任何重命名试用命令的情况下执行,我会得到这个输出,这样你就可以看到zip中存在该文件。它不是File类,而是Zip::ZipEntry类,我可以解析新名称。
mimetype is a file ? false
class ? Zip::ZipEntry
new filename #mimetype-new
第一次尝试(未注释)时,我得到以下错误:
mimetype is a file ? false
class ? Zip::ZipEntry
Uncaught exception: undefined method `get_entry' for mimetype:Zip::ZipEntry
/Users/.../app/lib/zip_rename.rb:45:in `block in renaming_zip'
...
第二次尝试(未注释)时,我得到以下错误:
Uncaught exception: No such file or directory - (mimetype, #mimetype-new)
/Users/.../app/lib/zip_rename.rb:48:in `rename'
/Users/.../app/lib/zxp_rename.rb:48:in `block in renaming_zip'
...
mimetype is a file ? false
class ? Zip::ZipEntry
new filename #mimetype-new
第三次尝试(未注释)时,我得到以下错误:
mimetype is a file ? false
class ? Zip::ZipEntry
new filename #mimetype-new
Uncaught exception: undefined method `rename' for mimetype:Zip::ZipEntry
/Users/.../app/lib/zip_rename.rb:49:in `block in renaming_zip'
...
要重命名条目,请对条目调用rename。
第一次尝试失败,因为您在entry
上调用get_entry
,它应该在ZipFile
上。
第二次尝试失败,因为代码以双引号结束字符串。
new_filename = entry.name.gsub('mimetype', '#mimetype-new')
第三次尝试失败,因为对象是mimetype:Zip::ZipEntry
而不是Zip::ZipEntry
正确的方法是
new_filename = "#mimetype-new"
Zip::ZipFile.open(zip_file).each do |zipfile|
files = zipfile.select(&:file?)
files.each do |file|
if entry.name == "mimetype"
entry.rename(entry.name, new_filename)
end
end
end
使用rubyzip:重命名zip中的文件
require 'zip'
old_name = 'mimetype'
new_filename = '#mimetype-new'
Zip::ZipFile.open(zip_file_path).each do |zipfile|
files = zipfile.select(&:file?)
file = files.find{|f| f.name == old_name}
zipfile.rename(file.name, new_filename) if file
end