Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - Renaming Files/Directories



Groovy provides File class which represents a directory or File object which have options to rename a file or directory.

Example - Renaming a File

File.renameTo(File file) method renames file to another file and return true it is able to rename the file. It returns false otherwise.

Example.groovy

// get a file 
def file = new File('data.txt')

// file to be used to rename the File
def fileNewName = new File('data1.txt')
 
// rename the File
if(file.renameTo(fileNewName)){
   println "File '${file.name}' renamed to '${fileNewName.name}'."
}else{
   println "Failed to rename file '${file.name}'."
}

Output

When we run the above program, we will get the following result.

File 'data.txt' renamed to 'data1.txt'.

Example - Renaming a Directory

File.renameTo(File file) method can be used to rename directories as well in the same fashion as it is used to rename a file.

Example.groovy

// get a directory 
def directory = new File('Sample')

// file to be used to rename the directory
def directoryNewName = new File('Sample1')
 
// rename the directory
if(directory.renameTo(directoryNewName)){
   println "Directory '${directory.name}' renamed to '${directoryNewName.name}'."
}else{
   println "Failed to rename directory '${directory.name}'."
}

Output

When we run the above program, we will get the following result.

Directory 'Sample' renamed to 'Sample1'.
Advertisements