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

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

Description

copy

License

Open Source License

Declaration

public static final void copy(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 {
    public static final void copy(File source, File destination)
            throws IOException {
        if (source.isDirectory()) {
            copyDirectory(source, destination);
        } else {//from w ww  .  j  a  va 2  s. c o  m
            copyFile(source, destination);
        }
    }

    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.");
        }

        if (destination.exists()) {
            throw new IllegalArgumentException("Destination ("
                    + destination.getPath() + ") exists.");
        }

        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()));
            }
        }
    }

    public static final void copyFile(File source, File destination)
            throws IOException {
        FileChannel sourceChannel = new FileInputStream(source)
                .getChannel();
        FileChannel targetChannel = new FileOutputStream(destination)
                .getChannel();
        sourceChannel.transferTo(0, sourceChannel.size(), targetChannel);
        sourceChannel.close();
        targetChannel.close();
    }
}

Related

  1. copy(File source, File dest)
  2. copy(File source, File dest)
  3. copy(File source, File dest)
  4. copy(File source, File dest)
  5. copy(File source, File dest, boolean preserveTime)
  6. copy(File source, File destination)
  7. copy(File source, File destination)
  8. copy(File source, File destination)
  9. copy(File source, File destination)