Here you can find the source of copy(final File fromFile, final File toFile)
Parameter | Description |
---|---|
fromFile | The existing File |
toFile | The new File |
true
if and only if the renaming succeeded; false
otherwise
public static boolean copy(final File fromFile, final File toFile)
//package com.java2s; /*/*from w w w . j a v a2s .co m*/ * Copyright (c) 2017 Eric A. Snell * * This file is part of eAlvaTag. * * eAlvaTag is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * eAlvaTag is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with eAlvaTag. If not, * see <http://www.gnu.org/licenses/>. */ 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 a File. * <p> * ToDo refactor AbstractTestCase to use this method as it contains an exact duplicate. * * @param fromFile The existing File * @param toFile The new File * * @return <code>true</code> if and only if the renaming succeeded; <code>false</code> otherwise */ public static boolean copy(final File fromFile, final File toFile) { try { copyThrowsOnException(fromFile, toFile); return true; } catch (IOException e) { e.printStackTrace(); return false; } } /** * Copy src file to dst file. FileChannels are used to maximize performance. * * @param source source File * @param destination destination File which will be created or truncated, before copying, if it already exists * * @throws IOException if any error occurS */ static void copyThrowsOnException(final File source, final File destination) throws IOException { // Must be done in a loop as there's no guarantee that a request smaller than request count will complete in one invocation. // Setting the transfer size more than about 1MB is pretty pointless because there is no asymptotic benefit. What you're trying // to achieve with larger transfer sizes is fewer context switches, and every time you double the transfer size you halve the // context switch cost. Pretty soon it vanishes into the noise. try (FileInputStream inStream = new FileInputStream(source); FileOutputStream outStream = new FileOutputStream(destination)) { final FileChannel inChannel = inStream.getChannel(); final FileChannel outChannel = outStream.getChannel(); final long size = inChannel.size(); long position = 0; while (position < size) { position += inChannel.transferTo(position, 1024L * 1024L, outChannel); } } //Closeables closed exiting try block in all circumstances } }