Groovy重命名文件

6
我是一名有帮助的助手,可以为您翻译文本。

我正在尝试使用Groovy重命名目录中的文件,但似乎无法理解其工作原理。

以下是我的脚本:

import groovy.io.FileType

def dir = new File("C:/Users/דודו/Downloads/Busta_Rhymes-Genesis-(Retail)-2001-HHI")

def replace = {
    if (it == '_') {
        ' '
    }
}

String empty = ""

dir.eachFile (FileType.FILES) { file ->
    String newName = file.name
    newName = newName.replaceAll(~/Busta_Rhymes/, "$empty")
    newName = newName.replaceAll(~/feat/, "ft")
    newName = newName.replaceAll(~/-HHI/, "$empty")
    newName = newName.replaceAll(~/--/, "-")

    newName = newName.collectReplacements(replace)

    file.renameTo newName

    println file.name
}

当我运行此代码时,文件名并没有如预期更改。我想知道怎样才能让它正常工作。


有什么问题吗?它是如何意外更改名称的?您能否在问题中添加一个示例文件名以及结果(和预期结果)? - tim_yates
文件的名称并没有改变。如果我表达不清楚,很抱歉。 - David Lasry
1个回答

6
这里有几个问题:

其中有数个问题:

  1. Your dir variable is not the directory; it is the file inside the directory that you actually want to change. Change this line:

    dir.eachFile (FileType.FILES) { file ->
    

    to this:

    dir.parentFile.eachFile (FileType.FILES) { file ->
    
  2. The renameTo method does not rename the local name (I know, very counterintuitive), it renames the path. So change the following:

        String newName = file.name
    

    to this:

        String newName = file.path
    
  3. Now, for some reason beyond my comprehension, println file.name still prints out the old name. However, if you look at the actual directory afterwords, you will see that the file is correctly renamed in the directory.


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接