Java Directory Copy nio copyDir(final Path fromPath, final Path toPath)

Here you can find the source of copyDir(final Path fromPath, final Path toPath)

Description

copy Dir

License

Apache License

Declaration

public static void copyDir(final Path fromPath, final Path toPath) throws IOException 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.io.IOException;

import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.StandardCopyOption;
import java.nio.file.attribute.BasicFileAttributes;

public class Main {
    public static void copyDir(final Path fromPath, final Path toPath) throws IOException {

        toPath.toFile().mkdirs();//from   ww  w.ja  va 2  s  .co m

        Files.walkFileTree(fromPath, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                Path targetPath = toPath.resolve(fromPath.relativize(dir));
                if (!Files.exists(targetPath)) {
                    Files.createDirectory(targetPath);
                }
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                Files.copy(file, toPath.resolve(fromPath.relativize(file)), StandardCopyOption.REPLACE_EXISTING);
                return FileVisitResult.CONTINUE;
            }
        });
    }
}

Related

  1. copyDir(File dir1, File dir2)
  2. copyDir(File sourceDir, File targetDir)
  3. copyDir(final String src, final String dest)
  4. copyDir(Path from, Path to, IProgressMonitor monitor)
  5. copyDir(String sourceDir, String targetDir)
  6. copyDir(String src, String dst)