Java FileChannel Copy copyFile(final File src, final File dst)

Here you can find the source of copyFile(final File src, final File dst)

Description

Copies the source file to the destination file

License

Open Source License

Parameter

Parameter Description
src the source file
dst the destination file

Exception

Parameter Description
IOException if there is a problem during the file copy

Declaration

public static void copyFile(final File src, final File dst)
        throws IOException 

Method Source Code

//package com.java2s;
/**// w  w  w.jav  a2  s. co  m
 * Copyright (c) 2009 Stephen Evanchik
 * 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:
 *  Stephen Evanchik - initial implementation
 */

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 {
    /**
     * Copies the source file to the destination file
     *
     * @param src
     *            the source file
     * @param dst
     *            the destination file
     * @throws IOException
     *             if there is a problem during the file copy
     */
    public static void copyFile(final File src, final File dst)
            throws IOException {
        if (!src.exists()) {
            throw new FileNotFoundException("File does not exist: "
                    + src.getAbsolutePath());
        }

        if (!dst.exists()) {
            dst.createNewFile();
        }

        FileChannel source = null;
        FileChannel destination = null;
        try {
            source = new FileInputStream(src).getChannel();
            destination = new FileOutputStream(dst).getChannel();

            destination.transferFrom(source, 0, source.size());
        } finally {
            if (source != null) {
                source.close();
            }

            if (destination != null) {
                destination.close();
            }
        }
    }
}

Related

  1. copyFile(FileInputStream fromFile, FileOutputStream toFile)
  2. copyFile(final File in, final File out)
  3. copyFile(final File in, final File out)
  4. copyFile(final File input, final File output)
  5. copyFile(final File src, final File dest)
  6. copyFile(final File srcFile, final File destFile)
  7. copyFile(final File srcFile, final File destFile)
  8. copyFile(final String src, final String dest)
  9. copyFile(final String src, final String dst)