Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Atomically move and rename a Path instance

Tags:

java

file

Given a Path path instance, I have the following questions:

  1. 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?

  2. 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.

like image 517
skiwi Avatar asked Feb 13 '23 11:02

skiwi


1 Answers

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:

  • this can fail with an AtomicMoveNotSupportedException if the option is not supported (for example if you are moving a file from a local hard drive to a network location).
  • The 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.
like image 193
assylias Avatar answered Feb 15 '23 23:02

assylias