How do I rename (not move) a file in Java 7?

java.is.for.desktop picture java.is.for.desktop · Dec 16, 2009 · Viewed 23.3k times · Source

I'm a bit confused with all these new File I/O classes in JDK7.

Let's say, I have a Path and want to rename the file it represents. How do I specify the new name, when again a Path is expected?

Path p = /* path to /home/me/file123 */;
Path name = p.getName(); /* gives me file123 */
name.moveTo(/* what now? */); /* how to rename file123 to file456? */

NOTE: Why do I need JDK7? Handling of symbolic links!

Problem is: I have to do it with files whose names and locations are known at runtime. So, what I need, is a safe method (without exceptional side-effects) to create a new name-Path of some old name-Path.

Path newName(Path oldName, String newNameString){
    /* magic */ 
}

Answer

Avner picture Avner · Nov 13, 2012

In JDK7, Files.move() provides a short and concise syntax for renaming files:

Path newName(Path oldName, String newNameString) {
    return Files.move(oldName, oldName.resolveSibling(newNameString));
}

First we're getting the Path to the new file name using Path.resolveSibling() and the we use Files.move() to do the actual renaming.