English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Grund教程

Java Flusskontrolle

Java Array

Java objektorientiert (I)

Java objektorientiert (II)

Java objektorientiert (III)

Java Ausnahmebehandlung

Java Liste (Liste)

Java Queue (Warteschlange)

Java Map-Kollektion

Java Set-Kollektion

Java Eingabe Ausgabe(I/O)

Java Reader/Writer

Java andere Themen

Datei umbenennen in Java-Programm

Java Example Comprehensive

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.

Beispiel: Datei mit Java umbenennen

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.

Java Example Comprehensive