Java FileChannel Copy copyFile(File from, File to)

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

Description

copy File

License

LGPL

Declaration

public static boolean copyFile(File from, File to) 

Method Source Code

//package com.java2s;
//License from project: LGPL 

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 boolean copyFile(File from, File to) {
        return copyFile(from, to, false);
    }/*from w ww  . j av a 2  s .  c o  m*/

    public static boolean copyFile(File from, File to, boolean withFilename) {
        if (!from.isFile()) {
            return false;
        }
        if (!from.exists()) {
            return false;
        }
        if (!withFilename) {
            to = new File(to, from.getName());
        }
        if (to.exists()) {
            to.delete();
        }

        try {
            to.createNewFile();
        } catch (IOException e) {
            return false;
        }

        FileChannel source = null;
        FileChannel destination = null;

        try {
            source = new FileInputStream(from).getChannel();
            destination = new FileOutputStream(to).getChannel();
            destination.transferFrom(source, 0, source.size());
        } catch (IOException e) {
            return false;
        } finally {
            try {
                if (source != null) {
                    source.close();
                }
                if (destination != null) {
                    destination.close();
                }
            } catch (IOException e) {
                return false;
            }
        }
        return true;
    }
}

Related

  1. copyChannel(ReadableByteChannel in, long length, FileChannel out)
  2. copyFile(File aFromFile, String aToFilename)
  3. copyFile(File copyFrom, File copyTo)
  4. copyFile(File file, String destDir)
  5. copyFile(File fileIn, File fileOut)
  6. copyFile(File from, File to)
  7. copyFile(File from, File to)
  8. copyFile(File from, File to)
  9. copyFile(File from, File to, long fromoffset, long tooffset, long size)