Java Path Copy nio copy(final Path source, final Path destination, final CopyOption... options)

Here you can find the source of copy(final Path source, final Path destination, final CopyOption... options)

Description

copy

License

Apache License

Declaration

public static void copy(final Path source, final Path destination, final CopyOption... options)
            throws IOException 

Method Source Code


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

import java.io.*;

import java.nio.file.*;

import java.nio.file.attribute.BasicFileAttributes;

public class Main {
    public static void copy(final Path source, final Path destination, final CopyOption... options)
            throws IOException {
        if (Files.notExists(destination)) {
            Files.createDirectories(destination);
        }//w ww .  j  av a2 s .c om

        Files.walkFileTree(source, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                String fileRelativePath = relativizePath(source, file);
                Path destFile = destination.resolve(fileRelativePath);
                Files.copy(file, destFile, options);
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                String dirRelativePath = relativizePath(source, dir);
                Path destDir = destination.resolve(dirRelativePath);
                Files.createDirectories(destDir);
                return FileVisitResult.CONTINUE;
            }
        });
    }

    public static String relativizePath(Path root, Path child) {
        String childPath = child.toAbsolutePath().toString();
        String rootPath = root.toAbsolutePath().toString();
        if (childPath.equals(rootPath)) {
            return "";
        }
        int indexOfRootInChild = childPath.indexOf(rootPath);
        if (indexOfRootInChild != 0) {
            throw new IllegalArgumentException(
                    "Child path " + childPath + "is not beginning with root path " + rootPath);
        }
        String relativizedPath = childPath.substring(rootPath.length(), childPath.length());
        while (relativizedPath.startsWith(root.getFileSystem().getSeparator())) {
            relativizedPath = relativizedPath.substring(1);
        }
        return relativizedPath;
    }
}

Related

  1. addCopyRight(Path p)
  2. copy(FileInputStream from, FileOutputStream to)
  3. copy(final File source, final File target)
  4. copy(Path from, Path to)
  5. copy(Path inPath, Path outPath)
  6. copy(Path source, Path destination)
  7. copy(Path source, Path destination)