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

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

Description

Copy file source to destination .

License

Open Source License

Parameter

Parameter Description
source Source file
destination Destination file

Exception

Parameter Description
IOException an exception

Declaration

public static void fileCopy(File source, File destination)
        throws IOException 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2011, 2012 Alex Bradley.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors://from   w  w  w.j a  v  a2s.co  m
 *    Alex Bradley - initial API and implementation
 *******************************************************************************/

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

public class Main {
    /**
     * Copy file {@code source} to {@code destination}.
     * @param source Source file
     * @param destination Destination file
     * @throws IOException
     */
    public static void fileCopy(File source, File destination)
            throws IOException {
        if (destination.exists()) {
            throw new IllegalArgumentException(
                    "Cannot overwrite existing file");
        }

        // cf. http://www.javalobby.org/java/forums/t17036.html
        FileChannel sourceChannel = null, destChannel = null;
        try {
            sourceChannel = new FileInputStream(source).getChannel();
            destChannel = new FileOutputStream(destination).getChannel();
            destChannel
                    .transferFrom(sourceChannel, 0, sourceChannel.size());
        } finally {
            if (sourceChannel != null) {
                sourceChannel.close();
            }
            if (destChannel != null) {
                destChannel.close();
            }
        }
    }
}

Related

  1. copyFile(final File source, final File target)
  2. copyFileByMapped(String sourcePath, String targetPath)
  3. copyToFile(final InputStream is, final File file)
  4. copyToTempFile(final InputStream is, final String prefix, final String suffix)
  5. copyToTmpFile(InputStream in, String prefix, String suffix)
  6. fileCopy(File source, File target)
  7. fileCopy(File sourceFile, File destFile)
  8. fileCopy(File src, File dest)
  9. fileCopy(final File dest, final File src)