Here you can find the source of copyFile(File original, File destination)
original
to the file destination
.
Parameter | Description |
---|---|
original | the original file |
destination | the destination file |
Parameter | Description |
---|---|
IOException | for exceptions during IO |
public static void copyFile(File original, File destination) throws IOException
//package com.java2s; /******************************************************************************* * Copyright 2015 DANS - Data Archiving and Networked Services * * 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 * /* w ww.java2s .c om*/ * 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.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; public class Main { /** * Copy the file <code>original</code> to the file <code>destination</code>. * * @param original * the original file * @param destination * the destination file * @throws IOException * for exceptions during IO */ public static void copyFile(File original, File destination) throws IOException { if (!original.exists()) { throw new FileNotFoundException("File not found: " + original.getName()); } if (original.isHidden()) { return; } if (original.equals(destination)) { throw new IOException("Cannot copy " + original.getName() + " into itself."); } if (original.isDirectory() && destination.isFile()) { throw new IOException("Cannot copy the contents of '" + original.getName() + "' to the file " + destination.getName()); } File finalDestination; if (destination.isDirectory()) { finalDestination = new File(destination, original.getName()); } else { finalDestination = destination; } if (original.isDirectory()) { finalDestination.mkdirs(); for (File f : original.listFiles()) { copyFile(f, finalDestination); } } else { FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(original); fos = new FileOutputStream(finalDestination); byte[] buffer = new byte[4096]; int read = fis.read(buffer); while (read != -1) { fos.write(buffer, 0, read); read = fis.read(buffer); } } finally { closeStreams(fis, fos); } } } private static void closeStreams(FileInputStream fis, FileOutputStream fos) throws IOException { try { if (fis != null) { fis.close(); } } finally { if (fos != null) { fos.close(); } } } }