Java Path Copy nio copy(Path source, Path target)

Here you can find the source of copy(Path source, Path target)

Description

copy

License

Open Source License

Declaration

public static void copy(Path source, Path target) throws IOException 

Method Source Code


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

import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;

public class Main {
    public static void copy(Path source, Path target) throws IOException {
        if (Files.isDirectory(source)) {
            if (Files.isDirectory(target)) {
                Files.walkFileTree(source, new SimpleFileVisitor<Path>() {
                    @Override// www . j  a v a  2s . c  o  m
                    public FileVisitResult preVisitDirectory(Path path, BasicFileAttributes basicFileAttributes)
                            throws IOException {
                        Path relative = source.relativize(path);
                        Path targetDir = target.resolve(relative);
                        if (!Files.exists(targetDir)) {
                            Files.createDirectory(targetDir);
                        }
                        return super.preVisitDirectory(path, basicFileAttributes);
                    }

                    @Override
                    public FileVisitResult visitFile(Path path, BasicFileAttributes basicFileAttributes)
                            throws IOException {
                        Path relative = source.relativize(path);
                        Path targetFile = target.resolve(relative);
                        Files.copy(path, targetFile);
                        return super.visitFile(path, basicFileAttributes);
                    }
                });
            } else if (!Files.exists(target)) {
                Files.createDirectories(target);
                copy(source, target);
            } else {
                throw new IOException("Target " + target + " is a file of the directory source " + target);
            }
        } else {
            if (Files.isDirectory(target)) {
                Files.copy(source, target);
            } else {
                Files.createDirectories(target.getParent());
                copy(source, target.getParent());
            }
        }
    }
}

Related

  1. copy(final Path source, final Path destination, final CopyOption... options)
  2. copy(Path from, Path to)
  3. copy(Path inPath, Path outPath)
  4. copy(Path source, Path destination)
  5. copy(Path source, Path destination)
  6. copy(Path source, Path target, CopyOption... options)
  7. copy(Path sourcePath, Path destinationPath)
  8. copy(Path sourcePath, Path targetPath)
  9. copy(Path src, Path dest, List globPattern)