Java FileChannel Copy copyFile(String source, String destination)

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

Description

This copies the given file to the given location (both names must be valid).

License

Open Source License

Parameter

Parameter Description
source the source file
destination the destination file

Exception

Parameter Description
IOException in case an I/O error occurs

Declaration

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

Method Source Code


//package com.java2s;
import java.io.*;
import java.nio.channels.*;

public class Main {
    /**//from ww w  .j  av a2s  . c om
     * This copies the given file to the given location (both names must be valid).
     * It just casts the Strings to {@link File}s and calls {@link #copyFile(String, String)}.
     *
     * @param source the source file
     * @param destination the destination file
     * @throws IOException in case an I/O error occurs
     */
    public static void copyFile(String source, String destination) throws IOException {
        copyFile(new File(source), new File(destination));
    }

    /**
     * This copies the given file to the given location (both names must be valid).
     * (modified after <a href="http://www.rgagnon.com/javadetails/java-0064.html">this webpage</a>.)
     *
     * @param source the source file
     * @param destination the destination file
     * @throws IOException in case an I/O error occurs
     */
    public static void copyFile(File source, File destination) throws IOException {

        FileChannel inChannel = new FileInputStream(source).getChannel();
        FileChannel outChannel = new FileOutputStream(destination).getChannel();

        try {
            int maxCount = (64 * 1024 * 1024) - (32 * 1024);
            long size = inChannel.size();
            long position = 0;
            while (position < size) {
                position += inChannel.transferTo(position, maxCount, outChannel);
            }
        } catch (IOException e) {
            throw e;
        } finally {
            if (inChannel != null) {
                inChannel.close();
            }
            if (outChannel != null) {
                outChannel.close();
            }
        }
    }
}

Related

  1. copyFile(String inName, String otName)
  2. copyFile(String input, String output)
  3. copyFile(String origPath, String destPath)
  4. copyFile(String source, String destination)
  5. copyFile(String source, String destination)
  6. copyFile(String source, String target)
  7. copyFile(String source, String target)
  8. copyFile(String sourceFile, String destFile)
  9. copyFile(String sourceFilename, String destFilename)