Java FileChannel Copy copyFile(String sourceFile, String destFile)

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

Description

Copies a file

License

Open Source License

Parameter

Parameter Description
sourceFile a parameter
destFile a parameter

Return

true if successful, false otherwise.

Declaration

public static boolean copyFile(String sourceFile, String destFile) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

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

public class Main {
    /**//from w w  w  .ja va 2  s  . c o m
     * Copies a file
     * @param sourceFile
     * @param destFile
     * @return true if successful, false otherwise.
     */
    public static boolean copyFile(String sourceFile, String destFile) {
        java.io.File source = new java.io.File(sourceFile);
        java.io.File dest = new java.io.File(destFile);
        try {
            copyFile(source, dest);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * Copies a file via java.io.FileUtils types.
     * @param sourceFile
     * @param destFile
     * @throws IOException
     */
    public static void copyFile(java.io.File sourceFile, java.io.File destFile) throws IOException {
        if (!destFile.exists()) {
            destFile.createNewFile();
        }

        FileChannel source = null;
        FileChannel destination = null;

        try {
            source = new FileInputStream(sourceFile).getChannel();
            destination = new FileOutputStream(destFile).getChannel();
            destination.transferFrom(source, 0, source.size());
        } finally {
            if (source != null) {
                source.close();
            }
            if (destination != null) {
                destination.close();
            }
        }
    }
}

Related

  1. copyFile(String source, String destination)
  2. copyFile(String source, String destination)
  3. copyFile(String source, String destination)
  4. copyFile(String source, String target)
  5. copyFile(String source, String target)
  6. copyFile(String sourceFilename, String destFilename)
  7. copyFile(String sourceFileName, String destinationFileName)
  8. copyFile(String src, String dest)
  9. copyFile(String srcFileName, String desFileName)