Dave's Brain

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.

Add a comment

Sign in to add a comment
Copyright © 2008-2018, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.