Given a Path path instance, I have the following questions:
How do I rename the file at which the path points, without resorting to the old File API if possible, I have not been able to find it anywhere yet?
Is it possible to atomically both move a physical file to a new directory and rename it at the same time?
I am using Java 8, new things for the Path class got added in for sure, not sure if the are of any help answering this question though.
Regarding your first question, since Java 7 you can use Files#move:
Files.move(path, targetPath);
If you need it to be atomic, you can use the ATOMIC_MOVE option:
import static java.nio.file.StandardCopyOption.ATOMIC_MOVE;
Files.move(path, targetPath, ATOMIC_MOVE);
Note that:
AtomicMoveNotSupportedException if the option is not supported (for example if you are moving a file from a local hard drive to a network location).REPLACE_EXISTING option, if used, is ignored and if the target file exists then it is implementation specific if the existing file is replaced or this method fails by throwing an IOException.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