Java File Copy nio copyFile(final File source, final File target)

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

Description

Copy a file from source to target.

License

Open Source License

Parameter

Parameter Description
source File
target File

Exception

Parameter Description
FileNotFoundException an exception
IOException an exception

Declaration

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

Method Source Code


//package com.java2s;

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

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

public class Main {
    /**/*from  w ww .  ja  va 2 s  . c  om*/
     * Copy a file from source to target.
     * 
     * @param source
     *            File
     * @param target
     *            File
     * @throws FileNotFoundException
     * @throws IOException
     */
    public static void copyFile(final File source, final File target) throws FileNotFoundException, IOException {
        FileChannel in = new FileInputStream(source).getChannel(), out = new FileOutputStream(target).getChannel();
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        while (in.read(buffer) != -1) {
            buffer.flip(); // Prepare for writing
            out.write(buffer);
            buffer.clear(); // Prepare for reading
        }
        out.close();
        in.close();
    }
}

Related

  1. copyFile(File f1, File f2)
  2. copyFile(File source, File dest, boolean visibleFilesOnly)
  3. copyFile(File src, File dest)
  4. copyFile(FileChannel srcFc, File dstFile)
  5. copyFile(final File source, final File dest)
  6. copyFile(final File source, final File target)
  7. copyFileByMapped(String sourcePath, String targetPath)
  8. copyToFile(final InputStream is, final File file)
  9. copyToTempFile(final InputStream is, final String prefix, final String suffix)