Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force rename a file in Java

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?

like image 399
Quintin Par Avatar asked Aug 31 '26 08:08

Quintin Par


1 Answers

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.

like image 160
Mnementh Avatar answered Sep 02 '26 22:09

Mnementh