Programming Tips - Java: What's the modern way to rename a file in Java?

Date: 2016jan30 Update: 2025oct3 Language: Java Q. Java: What's the modern way to rename a file in Java? A. Use Java7+'s Files.move() like this:
import java.io.IOException; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; class Demo { static boolean renameModern(final String fromName, final String toName) { Path fromPath = FileSystems.getDefault().getPath(fromName); Path toPath = FileSystems.getDefault().getPath(toName); try { Files.move(fromPath, toPath, StandardCopyOption.REPLACE_EXISTING); System.out.println("Renamed " + fromPath + " to " + toPath); } catch (IOException ex) { System.err.println("Could not rename because " + ex.toString()); return false; } return true; } public static final void main(String []args) { renameModern("hello.txt", "goodbye.txt"); } }
Output:
Renamed hello.txt to goodbye.txt
The old way uses File.rename() but it can not replace existing.