简体   繁体   中英

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.

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

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())));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM