Java File renameTo() Method
Example
Rename filename.txt to newname.txt:
import java.io.File;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
File myFile = new File("filename.txt");
myFile.createNewFile();
File newFile = new File("newname.txt");
newFile.delete(); // Delete newname.txt if it already exists
System.out.println(myFile.renameTo(newFile));
System.out.println(myFile.exists());
System.out.println(newFile.exists());
}
}
Definition and Usage
The renameTo() method gives a file or directory a new name.
The File object itself does not change. It still has the old path, so myFile.exists() returns false after the rename.
Note: On some systems, like Windows, renameTo() fails if a file with the new name already exists. This is why the example deletes newname.txt first.
Syntax
public boolean renameTo(File dest)
Parameter Values
| Parameter | Description |
|---|---|
| dest | Required. A File object with the new name (path). |
Technical Details
| Returns: | true if the file or directory was renamed, otherwise false. |
|---|
Related Pages
❮ File Methods