Here you can find the source of copyFileNio(File src, File dst)
Parameter | Description |
---|---|
src | Source Path |
dst | Destination Path |
Parameter | Description |
---|---|
IOException | an exception |
public static final boolean copyFileNio(File src, File dst) throws IOException
//package com.java2s; /******************************************************************************* * Copyright (c) 2011 MadRobot.//from ww w . ja v a2 s .c o m * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v2.1 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html * * Contributors: * Elton Kent - 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 { /** * Use NIO to copy a file * * @param src * Source Path * @param dst * Destination Path * @return * @throws IOException * @see {@link FileUtils#recursiveCopy(File, File, boolean, boolean)} */ public static final boolean copyFileNio(File src, File dst) throws IOException { FileChannel srcChannel = null, dstChannel = null; try { // Create channel on the source srcChannel = new FileInputStream(src).getChannel(); // Create channel on the destination dstChannel = new FileOutputStream(dst).getChannel(); // // Copy file contents from source to destination // dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); { // long theoretical_max = (64 * 1024 * 1024) - (32 * 1024); int safe_max = (64 * 1024 * 1024) / 4; long size = srcChannel.size(); long position = 0; while (position < size) { position += srcChannel.transferTo(position, safe_max, dstChannel); } } // Close the channels srcChannel.close(); srcChannel = null; dstChannel.close(); dstChannel = null; return true; } finally { try { if (srcChannel != null) { srcChannel.close(); } } catch (IOException e) { } try { if (dstChannel != null) { dstChannel.close(); } } catch (IOException e) { } } } }