Java FileChannel Copy copyFile(String source, String target)

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

Description

copy File

License

Open Source License

Declaration

public static void copyFile(String source, String target) throws Exception 

Method Source Code


//package com.java2s;
// it under the terms of the GNU General Public License as published by

import java.io.*;

import java.nio.channels.FileChannel;

public class Main {
    public static void copyFile(String source, String target) throws Exception {
        copyFile(new File(source), new File(target));
    }/*from   w ww .  ja  v a 2 s  .c  o  m*/

    /**
     * fast file copy
     *
     * @param source source file
     * @param target target file
     * @throws Exception if error occurs
     */
    public static void copyFile(File source, File target) throws Exception {

        FileInputStream fis = new FileInputStream(source);
        FileOutputStream fos = new FileOutputStream(target);
        FileChannel inChannel = fis.getChannel();
        FileChannel outChannel = fos.getChannel();

        // inChannel.transferTo(0, inChannel.size(), outChannel);
        // original -- apparently has trouble copying large files on Windows

        // magic number for Windows, 64Mb - 32Kb
        int maxCount = (64 * 1024 * 1024) - (32 * 1024);
        long size = inChannel.size();
        long position = 0;
        while (position < size) {
            position += inChannel.transferTo(position, maxCount, outChannel);
        }

        inChannel.close();
        outChannel.close();
        fis.close();
        fos.close();
    }
}

Related

  1. copyFile(String input, String output)
  2. copyFile(String origPath, String destPath)
  3. copyFile(String source, String destination)
  4. copyFile(String source, String destination)
  5. copyFile(String source, String destination)
  6. copyFile(String source, String target)
  7. copyFile(String sourceFile, String destFile)
  8. copyFile(String sourceFilename, String destFilename)
  9. copyFile(String sourceFileName, String destinationFileName)