Here you can find the source of copyFile(File source, File destination, boolean overwrite)
Parameter | Description |
---|---|
source | The source file. |
destination | The destination file. |
overwrite | <i>true</i> to delete the file if it already exists. |
Parameter | Description |
---|---|
IOException | Thrown if there is a problem copying or if the file already exists and<b>overwrite</b> is <i>false</i>. |
public static void copyFile(File source, File destination, boolean overwrite) throws IOException
//package com.java2s; /*// w w w . ja v a2s . c om * Copyright 2015 The OpenDCT Authors. All Rights Reserved * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.nio.channels.FileChannel; public class Main { /** * Copies a file. * * @param source The source file. * @param destination The destination file. * @param overwrite <i>true</i> to delete the file if it already exists. * @throws IOException Thrown if there is a problem copying or if the file already exists and * <b>overwrite</b> is <i>false</i>. */ public static void copyFile(File source, File destination, boolean overwrite) throws IOException { FileChannel inputChannel = null; FileChannel outputChannel = null; if (destination.exists()) { if (overwrite) { if (!destination.delete()) { throw new IOException( "Unable to delete the destination file."); } } else { throw new IOException("The file already exists."); } } try { inputChannel = new FileInputStream(source).getChannel(); outputChannel = new FileOutputStream(destination).getChannel(); outputChannel .transferFrom(inputChannel, 0, inputChannel.size()); } finally { if (inputChannel != null && inputChannel.isOpen()) { inputChannel.close(); } if (outputChannel != null && outputChannel.isOpen()) { outputChannel.close(); } } } }