Wednesday, October 10, 2007

File Renaming problem in Java

Ok, so you want to write a code to rename a file in Java. Simple as it may seem, there is a catch in it.

Let us cosider the following code:

File file = new File("toRename.txt");
File newfile = new File("renamed.txt");
file.renameTo(newfile);
System.out.println(file.getName());

What would be the output of the above snippet of code?
Answer seems like "renamed.txt" if the renaming is successful. But, no it is "toRename.txt".

Explanation
The physical file has been renamed to "renamed.txt" but the File object "file" still has the same fileName ("toRename.txt"). So, I tried to find the cause of the behavior, and found this link. One of the users there has mentioned that File is an immutable object. So, I cross-referenced the Java Docs for version 1.4.2 and found the confirmation "Instances of the File class are immutable; that is, once created, the abstract pathname represented by a File object will never change.".

Just one problem, why don't the Sun people make these highlighted in the documentation.

No comments: