NIOExtension.copyRecursively(...) cannot replace non-empty directories
The method NIOExtension.copyRecursively(Path source, Path target, CopyOption ... options)
does not provide any way to overwrite / replace non-empty directories.
Example
Given two directories source
and target
:
source target
├╴a.txt └╴foo.txt
├╴b.txt
├╴c.txt
└╴dirD
├╴d1.txt
├╴d2.txt
└╴d3.txt
copyRecursively(source, target) // throws FileAlreadyExistsException
copyRecursively(source, target, REPLACE_EXISTING) // throws DirectoryNotEmptyException
Solution
Add two CopyOption
s for defining the desired behaviour.
-
REPLACE_DIRECTORIES
will replace any non-empty directories in the target path. -
MERGE_DIRECTORIES
will merge directories in the target path and replace existing files.
These two options are mutually exclusive, but can only be used when combined with the (already existing) REPLACE_EXISTING
option.
Example
copyRecursively( copyRecursively(
source, target, source, target,
Initial REPLACE_EXISTING, REPLACE_EXISTING,
REPLACE_DIRECTORIES MERGE_DIRECTORIES
) )
source target target target
│ │ │ │
├╴a.txt ├╴a.txt ├╴a.txt ├╴a.txt
├╴b.txt │ ├╴b.txt ├╴b.txt
│ ├╴c.txt │ ├╴c.txt
│ │ │ │
├╴dirD ├╴dirD ├╴dirD ├╴dirD
│ ├╴d1.txt │ ├╴d1.txt │ ├╴d1.txt │ ├╴d1.txt
│ ├╴d2.txt │ ├╴d2.txt │ ├╴d2.txt │ ├╴d2.txt
│ └╴d3.txt │ └╴d3.txt │ └╴d3.txt │ └╴d3.txt
│ │ │ │
├╴dirE │ ├╴dirE ├╴dirE
│ ├╴e1.txt │ │ ├╴e1.txt │ ├╴e1.txt
│ ├╴e2.txt │ │ ├╴e2.txt │ ├╴e2.txt
│ └╴e3.txt │ │ └╴e3.txt │ └╴e3.txt
│ │ │ │
│ ├╴dirF │ ├╴dirF
│ │ ├╴f1.txt │ │ ├╴f1.txt
│ │ ├╴f2.txt │ │ ├╴f2.txt
│ │ └╴f3.txt │ │ └╴f3.txt
│ │ │ │
└╴dirG └╴dirG └╴dirG └╴dirG
├╴g1.txt │ ├╴g1.txt ├╴g1.txt
└╴g2.txt ├╴g2.txt └╴g2.txt ├╴g2.txt
└╴g3.txt └╴g3.txt