Trying to move files from a sub-directory along with the structure to a parent directory. And am not able to accomplish this using Files.move()
. To illustrate the issue please see the below directory structure.
$ tree
.
└── b
├── c
│ ├── cfile.gtxgt
│ └── d
│ ├── dfile.txt
│ └── e
└── x
└── y
└── z
├── 2.txt
└── p
├── file1.txt
└── q
├── file
├── file2.txt
└── r
└── 123.txt
I want to emulate the below move command via Java.
$ mv b/x/y/z/* b/c
b/x/y/z/2.txt -> b/c/2.txt
b/x/y/z/p -> b/c/p
And the output should be something similar to
$ tree
.
└── b
├── c
│ ├── 2.txt
│ ├── cfile.gtxgt
│ ├── d
│ │ ├── dfile.txt
│ │ └── e
│ └── p
│ ├── file1.txt
│ └── q
│ ├── file
│ ├── file2.txt
│ └── r
│ └── 123.txt
└── x
└── y
└── z
In this move all the files and directories under directory z
have been moved to c
.
I have tried to do this:
public static void main(String[] args) throws IOException{
String aPath = "/tmp/test/a/";
String relativePathTomove = "b/x/y/z/";
String relativePathToMoveTo = "b/c";
Files.move(Paths.get(aPath, relativePathTomove), Paths.get(aPath, relativePathToMoveTo), StandardCopyOption.REPLACE_EXISTING);
}
However this causes this exception to the thrown java.nio.file.DirectoryNotEmptyException: /tmp/test/a/b/c
and if the the REPLACE_EXISTING
option is taken out the code throws a java.nio.file.FileAlreadyExistsException: /tmp/test/a/b/c
.
This question has an answer that uses a recursive function to solve this problem. But in my case it will involve further complexity as I need to even re-created the sub-dir structure in the new location.
I have not tried the option of using the commons-io
utility method org.apache.commons.io.FileUtils#moveDirectoryToDirectory
as this code seems to be first copying files and then deleting them from the original location. And In my case the files are huge and hence this is not a preferred option.
How can I achieve the the move functionality in java without resorting to copying. Is individual file move my only option?
TLDR: How can I emulate the mv
functionality in java for moving sub dir with files and structure to parent directory.