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

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

Description

Safely copies files and directories with its content.

License

Open Source License

Parameter

Parameter Description
source path to the existing file.
destination path to the desired location.

Exception

Parameter Description
IllegalArgumentException thrown on failure to resolve filename conflict.
IOException thrown on filesystem error.

Declaration

public static void copy(Path source, Path destination) throws IllegalArgumentException, IOException 

Method Source Code


//package com.java2s;
// License as published by the Free Software Foundation; either

import java.io.IOException;

import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;

public class Main {
    /**/*from ww w .j  a v a2  s.  c om*/
     * Safely copies files and directories with its content.
     *
     * @param source
     *        path to the existing file.
     * @param destination
     *        path to the desired location.
     * @throws IllegalArgumentException
     *         thrown on failure to resolve filename conflict.
     * @throws IOException
     *         thrown on filesystem error.
     */
    public static void copy(Path source, Path destination) throws IllegalArgumentException, IOException {
        if (Files.isDirectory(source)) {
            if (Files.exists(destination)) {
                if (!Files.isDirectory(destination)) {
                    throw new IllegalArgumentException(
                            String.format("fail to copy %s to %s " + "because former is not a directory",
                                    source.toString(), destination.toString()));
                }
            } else {
                Files.createDirectory(destination);
            }
            final DirectoryStream<Path> subPaths = Files.newDirectoryStream(source);
            for (Path path : subPaths) {
                final Path relativePath = source.relativize(path);
                copy(path, destination.resolve(relativePath));
            }
            subPaths.close();

        } else {
            Files.copy(source, destination);
        }
    }
}

Related

  1. copy(FileInputStream from, FileOutputStream to)
  2. copy(final File source, final File target)
  3. copy(final Path source, final Path destination, final CopyOption... options)
  4. copy(Path from, Path to)
  5. copy(Path inPath, Path outPath)
  6. copy(Path source, Path destination)
  7. copy(Path source, Path target)
  8. copy(Path source, Path target, CopyOption... options)
  9. copy(Path sourcePath, Path destinationPath)