Rename/Move Files Using java.io.File API
1. Rename a File in Place
Rename a file in the original place is trivial by using renameTo() method in java.io.File class. The following code snapshot will change a file name from “oldName.pdf” to “newName.pdf”:
String oldName = “oldName.pdf”;
String newName = “newName.pdf”;
File f = new File(oldName);
f.renameTo(newName);
It is also easy to rename a file, and move the file to an existing directory. The following code will change the file name from “oldName.pdf” to “newName.pdf”, and also move the file from “C:\oldDir” to “C:\newDirsubDir” provide “C:\newDir\subDir” exists:
String oldDir = “C:\\oldDir\\”;
String oldName = “oldName.pdf”;
String newDir = “C:\\oldDir\subDir\\”;
String newName = “newName.pdf”;
File f = new File (oldDir, oldName);
f.renameTo(newDir + newName);
3. Rename/Move a File to an Directory that does not exist
The piece of code above won’t work if C:\newDir\subDir\ does not exist. However, we still can achieve our goal by a little more work. Here is how we do:
String oldDir = “C:\\oldDir\\”;
String oldName = “oldName.pdf”;
String newDir = “C:\\oldDir\\subDir\\”;
File pDir = new File(newDir);
pDir.mkroots();
String newName = “newName.pdf”;
File f = new File (oldDir, oldName);
f.renameTo(newDir + newName);