Java Directory Copy nio copyDirectory(String source, String destination)

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

Description

copy Directory

License

Open Source License

Declaration

public static void copyDirectory(String source, String destination) throws IOException 

Method Source Code

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

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import java.io.IOException;

import java.nio.channels.FileChannel;

public class Main {
    public static void copyDirectory(String source, String destination) throws IOException {
        File sourceDir = new File(source);
        File destDir = new File(destination);

        if (!sourceDir.exists() || !sourceDir.isDirectory()) {
            throw new IOException("Source directory " + source + " does not exist or is not a directory");
        }//  w  ww  .  jav  a2s  .c  om

        if (destDir.exists() && !destDir.isDirectory()) {
            throw new IOException("Destination directory " + destination + " does not exist or is not a directory");
        }

        if (!destDir.exists()) {
            if (!destDir.mkdirs()) {
                throw new IOException("Directory " + destination + " cannot be created");
            }
        }

        File[] files = sourceDir.listFiles();
        for (File file : files) {
            if (file.isFile()) {
                copyFile(file.getPath(), destination + File.separator + file.getName());
            } else if (!file.getAbsolutePath().equals(destDir.getAbsolutePath())) {
                copyDirectory(file.getPath(), destination + File.separator + file.getName());
            }
        }
    }

    /**
     * Copies a file.
     * 
     * @param source
     *            the name of the source file
     * @param destination
     *            the name of the destination file
     * @throws IOException
     */
    public static void copyFile(File source, File destination) throws IOException {
        FileChannel srcChannel = new FileInputStream(source).getChannel();
        FileChannel dstChannel = new FileOutputStream(destination).getChannel();

        dstChannel.transferFrom(srcChannel, 0, srcChannel.size());

        srcChannel.close();
        dstChannel.close();
    }

    public static void copyFile(String source, String destination) throws IOException {
        copyFile(new File(source), new File(destination));
    }
}

Related

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