English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Java complete list of examples
Dans ce tutoriel, nous allons apprendre à renommer un fichier en utilisant Java.
DansFichier JavaLa classe fournit la méthode renameTo() pour changer le nom du fichier. Si l'opération de renommage réussit, elle renvoie true, sinon false.
import java.io.File; class Main { public static void main(String[] args) { //Créer un objet fichier File file = new File("oldName"); //Créer un fichier try { file.createNewFile(); } catch(Exception e) { e.getStackTrace(); } //Créer un objet contenant le nouveau nom de fichier File newFile = new File("newName"); //Changer le nom du fichier boolean value = file.renameTo(newFile); if(value) { System.out.println("Le nom du fichier a été modifié."); } 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 filename, 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 name of the file has been changed.
If the operation cannot be successfulThe following message will be displayed.
The name cannot be changed.