Rename the file in Java

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

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

and if a new file exists, then it fails.

How do I rename a force?

+3
source share
2 answers

I think you need to do this manually - this means that you need to check if the target-name already exists as a file and delete it before doing the real renaming.

You can write a procedure to do this:

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

, .

. ( ) , .

+5

newFile :

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

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

Source: https://habr.com/ru/post/1728910/


All Articles