Java - File Rename by File Object


To rename a file, use the renameTo() method, which takes a File object to represent the new file:

// Rename old-dummy.txt to new_dummy.txt
File oldFile = new File("old_dummy.txt");
File newFile = new File("new_dummy.txt");

boolean fileRenamed = oldFile.renameTo(newFile);
if (fileRenamed) {
    System.out.println(oldFile + " renamed to " + newFile);
else {
    System.out.println("Renaming " + oldFile + " to " + newFile + " failed.");

renameTo() method returns true if renaming of the file succeeds; otherwise, it returns false.

File object is immutable. Once created, it always represents the same pathname.

After renaming a file, the old File object still represents the original pathname.

File object represents a pathname, not an actual file in a file system.

Related Topic