Sunday, October 14, 2007

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);

2. Rename/Move a File to an Existing Directory

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);


The last line of code will rename and also move the file to newDir , C:\newDir\subDir.

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);

The last two lines of code in red will create all directories along the path if they do not exist, and then rename and move the file to the new directory.