Java File Copy nio copy(File source, File destination)

Here you can find the source of copy(File source, File destination)

Description

Copies file using nio transfer method.

License

Open Source License

Parameter

Parameter Description
source file
destination file

Return

number of bytes copied

Declaration

public static long copy(File source, File destination) 

Method Source Code

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

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

import java.nio.channels.FileChannel;

import java.util.logging.Logger;

public class Main {
    /** jdk1.4 logger */
    private static Logger logger = Logger.getLogger("de.axelwernicke.mypod.util");

    /**//from   w ww  .  jav  a  2s.c o  m
     * Copies file using nio transfer method.
     * Since we get somtimes exceptions, lets try it up to ten times.
     *
     * @param source file
     * @param destination file
     * @return number of bytes copied
     */
    public static long copy(File source, File destination) {
        logger.entering("de.axelwernicke.mypod.util.FileUtils", "copy");

        long bytesCopied = -1;

        try {
            boolean copied = false;
            int tries = 0;
            FileChannel fic = new FileInputStream(source).getChannel();
            FileChannel foc = new FileOutputStream(destination).getChannel();

            do {
                try {
                    bytesCopied = foc.transferFrom(fic, 0, fic.size());
                    copied = true;
                } catch (IOException e) {
                    logger.info("copy try " + tries + " of 10 failed: " + destination + " " + e.getMessage());
                    tries++;
                }
            } while (!copied && (tries < 10));

            fic.close();
            foc.close();
        } catch (Exception e) {
            logger.warning("exception raised :" + e.getMessage());
        }

        logger.exiting("de.axelwernicke.mypod.util.FileUtils", "copy");

        return bytesCopied;
    }
}

Related

  1. copy(File source, File destination)
  2. copy(File source, File destination)
  3. copy(File source, File destination)
  4. copy(File source, File destination)
  5. copy(File source, File destination)
  6. copy(File source, File target)
  7. copy(File source, File target)
  8. copy(File source, File target)
  9. copy(File source, File target, FilenameFilter filter)