English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this tutorial, we will learn how to rename a file using Java.
InJava fileThe class provides the renameTo() method to change the file name. If the renaming operation is successful, it returns true; otherwise, it returns false.
import java.io.File; class Main { public static void main(String[] args) { //Create a file object File file = new File("oldName"); //Create a file try { file.createNewFile(); } catch(Exception e) { e.getStackTrace(); } //Create an object containing the new file name File newFile = new File("newName"); //Change the file name boolean value = file.renameTo(newFile); if(value) { System.out.println("The file name has been changed."); } else { System.out.println("The name cannot be changed."); } } }
In the above example, we created a file object named file. This object stores information about the specified file path.
File file = new File("oldName");
Then, we create a new file using the specified file path.
//Create a new file with the specified path file.createNewFile();
Here, we created another file object named newFile. This object stores information about the specified file path.
File newFile = new File("newFile");
To change the file name, we used the renameTo() method. The name specified by the newFile object is used to rename the file specified by the file object.
file.renameTo(newFile);
If the operation is successfulThe following message will be displayed.
The file name has been changed.
If the operation cannot be successfulThe following message will be displayed.
The name cannot be changed.