Java FileChannel Copy copyFile(File file, String destDir)

Here you can find the source of copyFile(File file, String destDir)

Description

copy File

License

Open Source License

Declaration

public static void copyFile(File file, String destDir) throws IOException 

Method Source Code

//package com.java2s;
/**/*from w ww. j av  a 2  s .c  o  m*/
 * Copyright(c) 2005 Dragonfly - created by FengChun
 * All Rights Reserved.
 * 
 * @license: Dragonfly Common License
 * @date 2005-5-16
 */

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 void copyFile(File file, String destDir) throws IOException {
        if (!isCanReadFile(file))
            throw new RuntimeException("The File can't read:" + file.getPath());
        if (!isCanWriteDirectory(destDir))
            throw new RuntimeException("The Directory can't write:" + destDir);

        FileChannel srcChannel = null;
        FileChannel dstChannel = null;
        try {
            // Create channel on the source
            srcChannel = new FileInputStream(file).getChannel();

            // Create channel on the destination
            dstChannel = new FileOutputStream(destDir + "/" + file.getName()).getChannel();

            // Copy file contents from source to destination
            dstChannel.transferFrom(srcChannel, 0, srcChannel.size());

        } catch (IOException e) {
            throw e;
        } finally {
            if (srcChannel != null)
                srcChannel.close();
            if (dstChannel != null)
                dstChannel.close();
        }
    }

    public static void copyFile(String destFile, String destDir) throws IOException {
        copyFile(new File(destFile), destDir);
    }

    public static boolean isCanReadFile(File file) {
        return file.exists() && file.isFile() && file.canRead();
    }

    public static boolean isCanWriteDirectory(String destDir) {
        File dir = new File(destDir);
        return dir.exists() && dir.isDirectory() && dir.canWrite();
    }
}

Related

  1. copyAll(File source, File targetDir)
  2. copyAndReplace(File from, File to)
  3. copyChannel(ReadableByteChannel in, long length, FileChannel out)
  4. copyFile(File aFromFile, String aToFilename)
  5. copyFile(File copyFrom, File copyTo)
  6. copyFile(File fileIn, File fileOut)
  7. copyFile(File from, File to)
  8. copyFile(File from, File to)
  9. copyFile(File from, File to)