Java Directory Copy nio copyDirectory(String fromPath, String toPath)

Here you can find the source of copyDirectory(String fromPath, String toPath)

Description

Copy given directory, sub-directories and files

License

Open Source License

Parameter

Parameter Description
from a file system path to the 'from' directory
to a file system path to the destination

Exception

Parameter Description
IOException an exception

Declaration

public static void copyDirectory(String fromPath, String toPath) throws IOException 

Method Source Code


//package com.java2s;
import java.io.File;
import java.io.IOException;
import java.nio.file.CopyOption;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

public class Main {
    /**//www .j  ava2  s .  com
     * Copy given directory, sub-directories and files
     * 
     * @param from
     *            a file system path to the 'from' directory
     * @param to
     *            a file system path to the destination
     * @throws IOException
     */
    public static void copyDirectory(String fromPath, String toPath) throws IOException {

        Path from = Paths.get(fromPath);
        Path to = Paths.get(toPath);
        CopyOption[] options = new CopyOption[] { StandardCopyOption.REPLACE_EXISTING,
                StandardCopyOption.COPY_ATTRIBUTES };
        Files.copy(from, to, options);
        for (File item : from.toFile().listFiles()) {
            if (item.isDirectory()) {
                copyDirectory(item.toString(), toPath + File.separator + item.getName());
            } else {
                Files.copy(Paths.get(item.toString()), Paths.get(toPath + File.separator + item.getName()),
                        options);
            }
        }
    }
}

Related

  1. copyDirectory(final File sourceFile, final File targetDir)
  2. copyDirectory(final File srcDir, final File destDir)
  3. copyDirectory(final Path source, final Path destination)
  4. copyDirectory(final Path source, final Path destination, List excludes)
  5. copyDirectory(Path source, ArrayList targets)
  6. copyDirectory(String source, String destination)
  7. copyDirectoryRecursively(File source, File target)
  8. copyDirectoryToDirectory(File srcDir, File destDir)
  9. copyDirNIO(File sourceLocation, File targetLocation)