views:

244

answers:

2

Can I use any utility to do a force rename of a file from Java.io?
I understand that Java 7 has these features, but I can’t use it...
If I do a

File tempFile = File.createTempFile();
tempFile.renameTo(newfile)

and if newfile exists then its fails.

How do I do a force rename?

+2  A: 

I think you have to do it manually - that means you have to check if the target-name exists already as a file and remove it before doing the real rename.

You can write a routine, to do it:

public void forceRename(File source, File target) throws IOException
{
   if (target.exists()) target.delete();
   source.renameTo(target)
}

The downside of this approach is, that after deleting and before renaming another process could create a new file with the name.

Another possibility could be therefore to copy the content of the source into the the target-file and deleting the source-file afterwards. But this would eat up more resources (depending on the size of the file) and should be done only, if the possibility of recreation of the deleted file is likely.

Mnementh
i wanted to avoid that race condition...
Quintin Par
Then try the second solution, copy the content and delete the old file. Should I provide example code?
Mnementh
A: 

You could always delete newFile first:

File newFile = ...
File file = ...

newFile.delete();
file.renameTo(newFile);
Adamski