Moving Directory Entries
The code below illustrates moving a file (./project/src/manifest.txt) to a new location (./project/bkup/manifest.txt). If the file exists at the new location, it is replaced by the source file.
Path srcFile = Path.of(“project”, “src”, “manifest.txt”);
Path destFile = Path.of(“project”, “bkup”, “manifest.txt”);
Files.move(srcFile, destFile, StandardCopyOption.REPLACE_EXISTING);
We can move a directory and its hierarchy (./project/bkup) to a new location (./project/ archive/backup). The directory (and its contents) are moved to the new location and renamed (backup).
Path srcDir = Path.of(“project”, “bkup”);
Path destDir = Path.of(“project”, “archive”, “backup”); // Parent path exists.
Files.move(srcDir, destDir);
Renaming Directory Entries
The move() method can be used to rename a directory entry. The code below illustrates renaming an existing file (Util.java). Its name is changed (UX.java), but not its contents.
Path oldFileName = Path.of(“project”, “backup”, “Util.java”);
Path newFileName = Path.of(“project”, “backup”, “UX.java”);
Files.move(oldFileName, newFileName);
Analogously, the code below illustrates renaming an existing directory (backup). Its name is changed (bkup), but not its hierarchy.
Path oldDirName = Path.of(“project”, “backup”);
Path newDirName = Path.of(“project”, “bkup”);
Files.move(oldDirName, newDirName);
Atomic Move
The enum constant StandardCopyOption.ATOMIC_MOVE can be specified in the move() method to indicate an atomic moveāthat is, an operation that is indivisible. It either completes in its entirety or it fails. The upshot of an atomic operation is that other threads will never see incomplete or partial results. An AtomicMoveNotSupported-Exception will be thrown if the file system does not support this feature.
In the following code, the file Util.java in the directory ./project/src/pkg is moved in an atomic operation to its new location ./project/archive/src/pkg.
Path srcFile = Path.of(“project”, “src”, “pkg”, “Util.java”);
Path destFile = Path.of(“project”, “archive”, “src”, “pkg”, “Util.java”);
Files.move(srcFile, destFile, StandardCopyOption.REPLACE_EXISTING,
StandardCopyOption.ATOMIC_MOVE);
Leave a Reply