Search code examples
javaoverwritefileutils

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


Solution

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