Here you can find the source of copyThrowsOnException(final File source, final File destination)
Parameter | Description |
---|---|
source | source File |
destination | destination File which will be created or truncated, before copying, if it already exists |
Parameter | Description |
---|---|
IOException | if any error occurS |
static void copyThrowsOnException(final File source, final File destination) throws IOException
//package com.java2s; /*/*w w w .j a v a 2 s .c o 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 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 } }