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

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

Description

Copy.

License

Apache License

Parameter

Parameter Description
source the source file or directory.
target the target file or directory.

Exception

Parameter Description
IOException when IO error occur.

Declaration

public static void copy(final File source, final File target) throws IOException 

Method Source Code


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

import java.io.*;

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 {
    /**/* w w  w  .jav  a 2 s .  c  om*/
     * Copy.
     *
     * @param source the source file or directory.
     * @param target the target file or directory.
     * @throws IOException when IO error occur.
     */
    public static void copy(final File source, final File target) throws IOException {
        if (source == null)
            throw new NullPointerException("source directory is null.");
        if (target == null)
            throw new NullPointerException("target directory is null.");

        if (source.isFile()) {
            File parentFolder = target.getParentFile();
            if (parentFolder != null) {
                parentFolder.mkdirs();
            }
            Files.copy(source.toPath(), target.toPath(), StandardCopyOption.COPY_ATTRIBUTES,
                    StandardCopyOption.REPLACE_EXISTING);
        } else if (source.isDirectory()) {
            Files.walkFileTree(source.toPath(), new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult preVisitDirectory(final Path dir, final BasicFileAttributes attrs)
                        throws IOException {
                    Files.createDirectories(target.toPath().resolve(source.toPath().relativize(dir)));
                    return FileVisitResult.CONTINUE;
                }

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

Related

  1. addCopyRight(Path p)
  2. copy(FileInputStream from, FileOutputStream to)
  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)