Java File Copy nio copy(File from, File to, final boolean recursive, Function excluded)

Here you can find the source of copy(File from, File to, final boolean recursive, Function excluded)

Description

copy

License

Open Source License

Declaration

public static void copy(File from, File to, final boolean recursive, Function<Path, Boolean> excluded)
            throws IOException 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.io.File;
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.EnumSet;
import java.util.function.Function;

public class Main {
    public static void copy(File from, File to, final boolean recursive, Function<Path, Boolean> excluded)
            throws IOException {
        final Path source = from.toPath();
        final Path target = to.toPath();

        if (recursive) {
            Files.walkFileTree(source, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE,
                    new SimpleFileVisitor<Path>() {
                        @Override
                        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                                throws IOException {
                            Path newDir = target.resolve(source.relativize(dir));
                            if (excluded.apply(newDir)) {
                                return FileVisitResult.SKIP_SUBTREE;
                            }/*w w w .  j  a  va 2  s .com*/

                            try {
                                Files.copy(dir, newDir, StandardCopyOption.COPY_ATTRIBUTES);
                            } catch (FileAlreadyExistsException e) {
                                if (!Files.isDirectory(newDir)) {
                                    throw e;
                                }
                            }
                            return FileVisitResult.CONTINUE;
                        }

                        @Override
                        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                            Files.copy(file, target.resolve(source.relativize(file)),
                                    StandardCopyOption.COPY_ATTRIBUTES);
                            return FileVisitResult.CONTINUE;
                        }
                    });
        } else {
            Files.copy(source, target, StandardCopyOption.COPY_ATTRIBUTES);
        }
    }
}

Related

  1. copy(File copied, File destination)
  2. copy(File file, File toDirectory)
  3. copy(File from, File to)
  4. copy(File from, File to)
  5. copy(File from, File to)
  6. copy(File in, File out)
  7. copy(File in, File out, boolean overwrite)
  8. copy(File inFile, File outFile)
  9. copy(File input, File output)