Java FileChannel Copy copyFile(File source, File target)

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

Description

A raw file copy function -- this is not public since no error checks are made as to the consistency of the file being copied.

License

Open Source License

Parameter

Parameter Description
source The source file. This is guaranteed to exist, and is guaranteed to be a file.
target The target file.

Exception

Parameter Description
IOException Throws an exception if the copy fails.

Declaration

private static void copyFile(File source, File target) throws IOException 

Method Source Code


//package com.java2s;
import java.io.*;

import java.nio.channels.FileChannel;

public class Main {
    /**//from w w  w .j ava2s.  c  o m
     * A raw file copy function -- this is not public since no error checks are made as to the
     * consistency of the file being copied. Use instead:
     * @see IOUtils#cp(java.io.File, java.io.File, boolean)
     * @param source The source file. This is guaranteed to exist, and is guaranteed to be a file.
     * @param target The target file.
     * @throws IOException Throws an exception if the copy fails.
     */
    private static void copyFile(File source, File target) throws IOException {
        FileChannel sourceChannel = new FileInputStream(source).getChannel();
        FileChannel targetChannel = new FileOutputStream(target).getChannel();

        // allow for the case that it doesn't all transfer in one go (though it probably does for a file cp)
        long pos = 0;
        long toCopy = sourceChannel.size();
        while (toCopy > 0) {
            long bytes = sourceChannel.transferTo(pos, toCopy, targetChannel);
            pos += bytes;
            toCopy -= bytes;
        }

        sourceChannel.close();
        targetChannel.close();
    }
}

Related

  1. copyFile(File source, File destination)
  2. copyFile(File source, File destination)
  3. copyFile(File source, File destination)
  4. copyFile(File source, File destination, boolean overwrite)
  5. copyFile(File source, File destination, long chunkSize, boolean overwrite)
  6. copyFile(File source, File target)
  7. copyFile(File source, File target)
  8. copyFile(File source, File target)
  9. copyFile(File source, File target)