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

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

Description

Recursively copies a directory from source to destination including all the files within the folders

License

Open Source License

Declaration

public static final void copyDirectory(File source, File 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 {
    /**/*from   w ww . ja v  a2s.co m*/
     * Recursively copies a directory from source to destination including
     * all the files within the folders
     */
    public static final void copyDirectory(File source, File destination) throws IOException {
        if (!source.isDirectory()) {
            throw new IllegalArgumentException("Source (" + source.getPath() + ") must be a directory.");
        }

        if (!source.exists()) {
            throw new IllegalArgumentException("Source directory (" + source.getPath() + ") doesn't exist.");
        }

        destination.mkdirs();
        File[] files = source.listFiles();

        for (File file : files) {
            if (file.isDirectory()) {
                copyDirectory(file, new File(destination, file.getName()));
            } else {
                copyFile(file, new File(destination, file.getName()));
            }
        }
    }

    /**
     * Copies a file from source to destination
     */
    private static final void copyFile(File source, File destination) throws IOException {
        FileInputStream inputStream = new FileInputStream(source);
        FileOutputStream outputStream = new FileOutputStream(destination);
        FileChannel sourceChannel = inputStream.getChannel();
        FileChannel targetChannel = outputStream.getChannel();
        sourceChannel.transferTo(0, sourceChannel.size(), targetChannel);
        sourceChannel.close();
        targetChannel.close();
        inputStream.close();
        outputStream.close();
    }
}

Related

  1. copyDirectory(File in, File out)
  2. copyDirectory(File in, File out)
  3. copyDirectory(File source, File dest, CopyOption... options)
  4. copyDirectory(File source, File destination)
  5. copyDirectory(File source, File destination)
  6. copyDirectory(File source, File destination, boolean recursive)
  7. copyDirectory(File source, File target, boolean acceptFileInUseError)
  8. copyDirectory(File sourceDir, File destinationDir)
  9. copyDirectory(File sourceDir, File targetDir)