Search code examples
javafile-iopathniojava-7

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


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 */ 
}

Solution

  • 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).