English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In diesem Tutorial werden wir lernen, wie man Dateien mit Java umbenennt.
inJava-DateiDie Klasse bietet die Methode renameTo() an, um den Dateinamen zu ändern. Erfolgt der Umbenennungsvorgang erfolgreich, wird true zurückgegeben,否则返回false.
import java.io.File; class Main { public static void main(String[] args) { //Dateiobjekt erstellen File file = new File("oldName"); //Eine Datei erstellen try { file.createNewFile(); } catch(Exception e) { e.getStackTrace(); } //Ein Objekt erstellen, das den neuen Dateinamen enthält File newFile = new File("newName"); //Dateiname ändern boolean value = file.renameTo(newFile); if(value) { System.out.println("Dateiname wurde geändert."); } 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 successfulThen the following message will be displayed.
The file name has been changed.
If the operation cannot be successfulThen the following message will be displayed.
The name cannot be changed.