Java File Copy nio copy(File sourceFile, File destFile)

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

Description

copy

License

Apache License

Declaration

public static boolean copy(File sourceFile, File destFile) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

public class Main {
    public static boolean copy(File sourceFile, File destFile) {
        try {/*from   www  .j a va 2s. co m*/
            copyFile(sourceFile, destFile);
            return true;
        } catch (IOException ioe) {
            System.out.println("File copy failed: " + ioe);
            return false;
        }
    }

    public static void copyFile(File sourceFile, File destFile) throws IOException {
        if (!destFile.exists()) {
            destFile.createNewFile();
        }
        FileInputStream fIn = null;
        FileOutputStream fOut = null;
        FileChannel source = null;
        FileChannel destination = null;
        try {
            fIn = new FileInputStream(sourceFile);
            source = fIn.getChannel();
            fOut = new FileOutputStream(destFile);
            destination = fOut.getChannel();
            long transfered = 0;
            long bytes = source.size();
            while (transfered < bytes) {
                transfered += destination.transferFrom(source, 0, source.size());
                destination.position(transfered);
            }
        } finally {
            if (source != null) {
                source.close();
            } else if (fIn != null) {
                fIn.close();
            }
            if (destination != null) {
                destination.close();
            } else if (fOut != null) {
                fOut.close();
            }
        }
    }
}

Related

  1. copy(File source, File target)
  2. copy(File source, File target)
  3. copy(File source, File target)
  4. copy(File source, File target, FilenameFilter filter)
  5. copy(File sourceFile, File destFile)
  6. copy(File sourceFile, File destinationFile)
  7. copy(File sourceFile, File targetFile)
  8. copy(File src, File dest)
  9. copy(File src, File dest)