Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rename file onto another in java

Tags:

java

file

I have a file I need to rename to that of an existing file. This is a copy, modify, replace original operation on an existing JAR file. I've got the first two steps done, I just need help with the replace original bit. What's the best way to rename the new version of the JAR to that of the old. The old JAR doesn't need preserving and I don't want to have a copy of the new with its initial name sticking around.

I have commons lang and io already, so if there's a method I've missed, that would be great.

like image 490
sblundy Avatar asked Jan 22 '26 21:01

sblundy


2 Answers

Java.io.File.renameTo(java.io.File)

You might need to call File.delete() first on the original file first - some systems won't rename a file onto an existing file.

like image 63
Alnitak Avatar answered Jan 24 '26 09:01

Alnitak


You're going to need to create two java.io.File objects: one for the new file, one for the old file.

Lets call these oldFile and newFile.

oldFile.delete()
newFile.renameTo(oldFile);

Edit: mmyers beat me to it.

like image 42
Powerlord Avatar answered Jan 24 '26 11:01

Powerlord