Groovy rename a file

David Lasry picture David Lasry · Sep 30, 2016 · Viewed 8.1k times · Source

I'm trying to rename files in a directory using Groovy but I can't seem to understand how it works.

Here is my script:

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
}

When I run this, the names of the files aren't changed as expected. I'm wondering how could I get this to work.

Answer

BalRog picture BalRog · Sep 30, 2016

There are a number of things wrong here:

  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.