Java FileChannel Copy copyFile(File source, File target)

Here you can find the source of copyFile(File source, File target)

Description

Inspired by http://stackoverflow.com/questions/106770/standard-concise-way-to-copy-a-file-in-java/115086#115086

License

Creative Commons License

Parameter

Parameter Description
source a parameter
target a parameter

Exception

Parameter Description
IOException an exception

Declaration

public static void copyFile(File source, File target) throws IOException 

Method Source Code

//package com.java2s;
/**//from  www  . j a v a 2  s  . c o m
 * Source: http://stackoverflow.com/questions/453018/number-of-lines-in-a-file-in-java
 * Licensed under http://creativecommons.org/licenses/by-sa/3.0/
 */

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import java.nio.channels.FileChannel;

public class Main {
    /**
     * Inspired by http://stackoverflow.com/questions/106770/standard-concise-way-to-copy-a-file-in-java/115086#115086
     * 
     * @param source
     * @param target
     * @throws IOException 
     */
    public static void copyFile(File source, File target) throws IOException {
        if (!target.exists()) {
            target.createNewFile();
        }

        FileChannel sourceChannel = null;
        FileChannel targetChannel = null;

        try {
            sourceChannel = new FileInputStream(source).getChannel();
            targetChannel = new FileOutputStream(target).getChannel();

            targetChannel.transferFrom(sourceChannel, 0, sourceChannel.size());
        } finally {
            if (sourceChannel != null) {
                sourceChannel.close();
            }
            if (targetChannel != null) {
                targetChannel.close();
            }
        }

    }

    public static boolean exists(String path) {
        return (new File(path)).exists();
    }
}

Related

  1. copyFile(File source, File destination, long chunkSize, boolean overwrite)
  2. copyFile(File source, File target)
  3. copyFile(File source, File target)
  4. copyFile(File source, File target)
  5. copyFile(File source, File target)
  6. copyFile(File sourceFile, File destFile)
  7. copyFile(File sourceFile, File destFile)
  8. copyFile(File sourceFile, File destFile)
  9. copyFile(File sourceFile, File destFile)