Java Program to Rename a File
Last Updated :
09 Nov, 2020
Changing the name of the file is known as Renaming the file. Rename operation is possible using renameTo() method belongs to the File class in java.
A. 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.
Below is the implementation of the above approach.
Java
import java.io.File;
public class GFG {
public static void main(String[] args)
{
File file = new File( "/home/mayur/Folder/GFG.java" );
File rename = new File( "/home/mayur/Folder/HelloWorld.java" );
boolean flag = file.renameTo(rename);
if (flag == true ) {
System.out.println( "File Successfully Rename" );
}
else {
System.out.println( "Operation Failed" );
}
}
}
|
Output:
File Successfully Rename
Before Program Execution
After Program Execution
B. 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
Java
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 Rename
Before Program Execution
After Program Execution
Share your thoughts in the comments
Please Login to comment...