Java FileChannel Copy copyFile(String sourceFilename, String destFilename)

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

Description

copy File

License

Open Source License

Parameter

Parameter Description
sourceFilename a parameter
destFilename a parameter

Exception

Parameter Description
IOException an exception

Declaration

@SuppressWarnings("resource")
public static void copyFile(String sourceFilename, String destFilename) 

Method Source Code

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

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

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

public class Main {
    /***********************************************************
     * @param sourceFilename/*from   w w w.j  av  a 2  s  .c o  m*/
     * @param destFilename
     * @throws IOException
     ***********************************************************/
    @SuppressWarnings("resource")
    public static void copyFile(String sourceFilename, String destFilename) {
        File sourceFile = new File(sourceFilename);
        File destFile = new File(destFilename);

        // System.out.println("Copying file " + sourceFilename + " to " +
        // destFilename);

        if (!sourceFile.exists()) {
            System.out.println("ERROR: Source file " + sourceFilename + " does not exist!");
            return;
        }

        try {
            if (!destFile.exists()) {
                destFile.createNewFile();
            }
            FileChannel source = null;
            FileChannel destination = null;
            source = new FileInputStream(sourceFile).getChannel();
            destination = new FileOutputStream(destFile).getChannel();

            if (destination != null && source != null)
                destination.transferFrom(source, 0, source.size());

            if (source != null)
                source.close();

            if (destination == null)
                System.out.println("ERROR: Destination file " + destFilename + " was not created!");
            else
                destination.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Related

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