Java FileChannel Copy copyFile(File in, File out)

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

Description

Copies a file.

License

Open Source License

Parameter

Parameter Description
in a parameter
out a parameter

Return

success.

Declaration

public static boolean copyFile(File in, File out) 

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 {
    /**//from  w  ww. j  a v a2s  .c om
     * Copies a file. Does NOT check if out already exists. Will overwrite out
     * if it already exists.
     * 
     * @param in
     * @param out
     * @return success.
     */
    public static boolean copyFile(File in, File out) {
        if (!in.exists()) {
            System.err.println("File '" + in.getName() + "' does not exist.");
            return false;
        }
        boolean success = false;
        try {
            FileChannel inChannel = new FileInputStream(in).getChannel();
            FileChannel outChannel = new FileOutputStream(out).getChannel();
            // magic number for Windows, 64Mb - 32Kb)
            int maxCount = (64 * 1024 * 1024) - (32 * 1024);
            long size = inChannel.size();
            long position = 0;
            while (position < size) {
                position += inChannel.transferTo(position, maxCount, outChannel);
            }
            if (inChannel != null)
                inChannel.close();
            if (outChannel != null)
                outChannel.close();
            if (in.length() == out.length())
                success = true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return success;
    }
}

Related

  1. copyFile(File from, File to)
  2. copyFile(File from, File to)
  3. copyFile(File from, File to)
  4. copyFile(File from, File to, long fromoffset, long tooffset, long size)
  5. copyFile(File in, File out)
  6. copyFile(File in, File out)
  7. copyFile(File in, File out)
  8. copyFile(File in, File out)
  9. copyFile(File in, File out)