Java – file.renameTo() return false

30 10 2012

In one of my program, the file.renameTo() returned false and failed to rename/move the file. However, it worked on other linux servers and window env.

File tmp = null;
tmp = File.createTempFile(report.getName(), null)
//.. do somthing...
tmp.renameTo(otherfile)

After some googling, I find the problem here.

The root cause is, renameTo() only works in same filesystem (or same disk). In my case, the tmp and otherfile is on two different disks, that why it returns false.

I check the Java Doc , although it did mention, I think it should be highlighted or explain in more details.

Below is extracted from Javadoc.

public boolean renameTo(File dest)

Renames the file denoted by this abstract pathname.
Many aspects of the behavior of this method are inherently platform-dependent: The rename operation might not be able to move a file from one filesystem to another, it might not be atomic, and it might not succeed if a file with the destination abstract pathname already exists. The return value should always be checked to make sure that the rename operation was successful.


Actions

Information

Leave a comment