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

You have a path string and you need to create a Path instance. You can do this with the getPath method or resolve. Here's one way:

Path dir = oldFile.getParent();        
Path fn = oldFile.getFileSystem().getPath(newNameString);
Path target = (dir == null) ? fn : dir.resolve(fn);        
oldFile.moveTo(target); 

Note that it checks if parent is null (looks like your solution don't do that).


OK, after trying everything out, it seems I found the right method:

// my helper method
Path newName(Path oldFile, String newNameString){
    // the magic is done by Path.resolve(...)
    return oldFile.getParent().resolve(newNameString);
}

// so, renaming is done by:
oldPath.moveTo(newName(oldFile, "newName"));

If you take a look at Apache Commons IO there's a class called FileNameUtils. This does a ton of stuff wrt. file path names and will (amongst other things) reliably split up path names etc. I think that should get you a long way towards what you want.


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.