Java File Copy nio copyFile(File f1, File f2)

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

Description

Copy file

License

Open Source License

Parameter

Parameter Description
f1 File
f2 File

Exception

Parameter Description
IOException ex

Declaration

public static void copyFile(File f1, File f2) throws IOException 

Method Source Code

//package com.java2s;

import java.io.File;
import java.io.FileInputStream;

import java.io.FileOutputStream;
import java.io.IOException;

import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class Main {
    /**/*from   ww  w  .  ja  v a2s.com*/
     * Copy file
     * 
     * @param f1 File
     * @param f2 File
     * @throws IOException ex
     */
    public static void copyFile(File f1, File f2) throws IOException {
        if (f1 == null || f2 == null || !f1.exists()) {
            return;
        }
        int length = 2097152;
        FileInputStream in = new FileInputStream(f1);
        FileOutputStream out = new FileOutputStream(f2);
        FileChannel inC = in.getChannel();
        FileChannel outC = out.getChannel();
        ByteBuffer b = null;
        while (true) {
            if (inC.position() == inC.size()) {
                inC.close();
                outC.close();
                return;
            }
            if ((inC.size() - inC.position()) < length) {
                length = (int) (inC.size() - inC.position());
            } else {
                length = 2097152;
            }

            b = ByteBuffer.allocateDirect(length);
            inC.read(b);
            b.flip();
            outC.write(b);
            outC.force(false);
        }
    }
}

Related

  1. copy(File srcDir, File relSrcFile, File destDir, File relDestFile)
  2. copy(File srcfile, File destfile)
  3. copy(File srcFile, File dstFile)
  4. copy(File srcFileOrDir, File targetFileOrDir)
  5. copy(File toFile, File fromFile)
  6. copyFile(File source, File dest, boolean visibleFilesOnly)
  7. copyFile(File src, File dest)
  8. copyFile(FileChannel srcFc, File dstFile)
  9. copyFile(final File source, final File dest)