Renaming a file means changing its existing name without changing the file's content. Java provides different ways to rename a file, including the renameTo() method of the File class and the move() method of the Files class.
- The Files.move() method can rename a file by moving it to a new path with a different name.
- resolveSibling() can be used with Files.move() to create the new file path in the same directory.
Methods Used To Rename a File
There are several ways to rename a file in Java, depending on the approach and API being used.
1. renameTo() Method
The renameTo() method is used to rename the abstract pathname of a file to a given pathname. The method returns a boolean value i.e. returns true if the file is renamed else returns false.
Approach
- Create an object of the File class and replace the file path with the path of the directory.
- Create another object of the File class and replace the file path with the renaming path of the directory.
- Use renameTo() method.
- If rename operation successful then the function returns true.
- Else returns false.
import java.io.File;
public class GFG {
public static void main(String[] args)
{
// Create an object of the File class
// Replace the file path with path of the directory
File file = new File("/home/mayur/Folder/GFG.java");
// Create an object of the File class
// Replace the file path with path of the directory
File rename = new File("/home/mayur/Folder/HelloWorld.java");
// store the return value of renameTo() method in
// flag
boolean flag = file.renameTo(rename);
// if renameTo() return true then if block is
// executed
if (flag == true) {
System.out.println("File Successfully Rename");
}
// if renameTo() return false then else block is
// executed
else {
System.out.println("Operation Failed");
}
}
}
Output:
File Successfully RenameBefore Program Execution

After Program Execution

2. move() Method
Rename of file can be done using move the contents of the first file to a new file and deleting the previous file. Java is handling this operation using resolveSibiling method. It is used to resolve the given path against this path’s parent path
import java.nio.file.*;
import java.io.IOException;
public class GFG {
public static void main(String[] args)
throws IOException
{
Path oldFile
= Paths.get("/home/mayur/Folder/GFG.java");
try {
Files.move(oldFile, oldFile.resolveSibling(
"HelloWorld.java"));
System.out.println("File Successfully Rename");
}
catch (IOException e) {
System.out.println("operation failed");
}
}
}
Output:
File Successfully RenameBefore Program Execution

After Program Execution
