[英]FileUtils: Skips files that are already in destination and copy rest of the files
I am using the following method to transfer files between two directories using java.我正在使用以下方法使用 java 在两个目录之间传输文件。
FileUtils.copyDirectory(sourceDir, destinationDir,fileFilter,false);
But if a file with the same name is also found in the destination directory, the file from source overwrites it.但是,如果在目标目录中也找到同名文件,源文件将覆盖它。 What I want is to exclude those files which also exist in destination and copy rest of them, ultimately preventing overwriting..
我想要的是排除目标中也存在的那些文件并复制其中的 rest,最终防止覆盖..
One way is to write it yourself:一种方法是自己写:
try (Stream<Path> files = Files.walk(sourceDir.toPath())
.filter(f -> fileFilter.accept(f.toFile()))) {
files.forEach(src -> {
Path dest = destinationDir.toPath().resolve(
sourceDir.toPath().relativize(src));
if (!Files.exists(dest)) {
try {
if (Files.isDirectory(src)) {
Files.createDirectories(dest);
} else {
Files.copy(src, dest,
StandardCopyOption.COPY_ATTRIBUTES);
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
})
}
Or, you could just modify your filter:或者,您可以只修改过滤器:
FileFilter oldFilter = fileFilter;
fileFilter = f -> oldFilter.accept(f) &&
!Files.exists(destinationDir.toPath().resolve(
sourceDir.toPath().relativize(f.toPath())));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.