Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

You could always delete newFile first:

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

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

I was unable to rename whenever a folder is open. Setting the following property in Java solved my issue:

dirToRename.setExecutable(true); 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top