1

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

2 回答 2

0

要重命名条目,请在条目上调用 rename。

第一次尝试失败,因为您正在调用get_entryentry它应该打开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
于 2013-03-29T18:45:28.817 回答
0

要使用ruby ​​zip 重命名 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
于 2015-09-27T13:58:05.203 回答