Java FileChannel Copy copyNio(final File source_file, final File destination_file)

Here you can find the source of copyNio(final File source_file, final File destination_file)

Description

copy Nio

License

Open Source License

Parameter

Parameter Description
source_file a parameter
destination_file a parameter

Exception

Parameter Description
IOException an exception

Declaration

public final static void copyNio(final File source_file, final File destination_file) throws IOException 

Method Source Code

//package com.java2s;
/*//from w  w  w.j  av  a  2s .c  om
 * Copyright (c) 2012 Diamond Light Source Ltd.
 *
 * 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
 */

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

import java.io.IOException;

import java.nio.channels.FileChannel;

public class Main {
    /**
     * @param source_file
     * @param destination_file
     * @throws IOException
     */
    public final static void copyNio(final File source_file, final File destination_file) throws IOException {

        if (!source_file.exists()) {
            return;
        }

        final File parTo = destination_file.getParentFile();
        if (!parTo.exists()) {
            parTo.mkdirs();
        }
        if (!destination_file.exists()) {
            destination_file.createNewFile();
        }

        FileChannel srcChannel = null, dstChannel = null;
        try {
            // Create channel on the source
            srcChannel = new FileInputStream(source_file).getChannel();

            // Create channel on the destination
            dstChannel = new FileOutputStream(destination_file).getChannel();

            // Copy file contents from source to destination
            dstChannel.transferFrom(srcChannel, 0, srcChannel.size());

            // Close the channels
        } finally {
            if (srcChannel != null) {
                srcChannel.close();
            }
            if (dstChannel != null) {
                dstChannel.close();
            }
        }
    }
}

Related

  1. copyFileUsingFileChannels(File source, File dest)
  2. copyFolder(File fin, File fout)
  3. copyFromZip(ZipFile zipFile, String locationInBundle, File destination)
  4. copyInternal(FileInputStream in, FileOutputStream out)
  5. copyLarge(FileInputStream in, FileOutputStream out)
  6. copyRec(File src, File dst)
  7. copyStream(InputStream in, long length, File out)
  8. copyStreamToFile(InputStream inStream, File file)
  9. copyThrowsOnException(final File source, final File destination)