我正在尝试重命名 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'
...