Java File Copy nio copy(File in, File out)

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

Description

copy

License

Open Source License

Declaration

public static void copy(File in, File out) 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 copy(File in, File out) throws IOException {
        if (in.exists() && in != null && out != null) {
            if (!out.exists()) {
                if (in.isDirectory()) {
                    out.mkdirs();/*ww w  . j a va2  s .  c o m*/
                } else {
                    out.createNewFile();
                }
            }
            String source = in.isDirectory() ? "directory" : "file";
            String target = out.isDirectory() ? "directory" : "file";
            if (!source.equals(target)) {
                throw new IOException("Can't duplicate " + source + " as " + target);
            } else {
                if (source.equals("directory")) {
                    File[] files = in.listFiles();
                    for (File file : files) {
                        copy(file, new File(out, file.getName()));
                    }
                } else {
                    FileChannel inCh = new FileInputStream(in).getChannel();
                    FileChannel outCh = new FileOutputStream(out).getChannel();
                    inCh.transferTo(0, inCh.size(), outCh);
                }
            }
        }
    }
}

Related

  1. copy(File file, File toDirectory)
  2. copy(File from, File to)
  3. copy(File from, File to)
  4. copy(File from, File to)
  5. copy(File from, File to, final boolean recursive, Function excluded)
  6. copy(File in, File out, boolean overwrite)
  7. copy(File inFile, File outFile)
  8. copy(File input, File output)
  9. copy(File inputFile, OutputStream out)