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

Date: 2016jan30
Language: Java

Q.  What's the modern way to rename a file in Java?

A.  Use Java7+'s Files.move() like this:

import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; 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); } catch (IOException e) { return false; } return true; }
The old way uses File.rename() but it can not replace existing.