Java File Copy nio copy(File file, File toDirectory)

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

Description

Copies a file to the specified directory.

License

Apache License

Parameter

Parameter Description
file the file to be copied.
toDirectory the directory to which the file should be copied.

Exception

Parameter Description
IOException in case of errors

Return

file object to the copied file.

Declaration

public static File copy(File file, File toDirectory) throws IOException 

Method Source Code


//package com.java2s;
//License from project: Apache 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 w  w. jav a2s  .  c o m*/
     * Copies a file to the specified directory.
     * 
     * @param file          the file to be copied.
     * @param toDirectory   the directory to which the file should be copied.
     * 
     * @return file object to the copied file.
     * 
     * @throws IOException in case of errors
     */
    public static File copy(File file, File toDirectory) throws IOException {

        if (file == null || !file.exists() || !file.canRead()) {
            throw new IOException("Unable to find source file to be copied " + file);
        }
        String basename = file.getName();

        File destFile = new File(toDirectory, basename.toString());

        if (!toDirectory.exists())
            toDirectory.createNewFile();

        FileChannel fcSrc = null;
        FileChannel fcDst = null;
        try {
            fcSrc = new FileInputStream(file).getChannel();
            fcDst = new FileOutputStream(destFile).getChannel();
            fcDst.transferFrom(fcSrc, 0, fcSrc.size());
        } finally {
            if (fcSrc != null)
                fcSrc.close();
            if (fcDst != null)
                fcDst.close();
        }

        return destFile;
    }
}

Related

  1. copy(File a, File b)
  2. copy(File base_path, File in, File out)
  3. copy(File copied, File destination)
  4. copy(File from, File to)
  5. copy(File from, File to)
  6. copy(File from, File to)
  7. copy(File from, File to, final boolean recursive, Function excluded)