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 */ }
File from = new File(directory, "currentFileName"); For safety, Use the File. renameTo() .
In Java we can rename a file using renameTo(newName) method that belongs to the File class. Parameters: dest – The new abstract pathname for the existing abstract pathname.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With