Here you can find the source of copyFile(File sourceFile, File destFile)
Parameter | Description |
---|---|
IOException | an exception |
public static void copyFile(File sourceFile, File destFile) throws IOException
//package com.java2s; /******************************************************************************* * Copyright 2011 Google Inc. All Rights Reserved. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * 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.// ww w. j av a 2s . com *******************************************************************************/ import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class Main { /** * Copies the source file into the destination file. The destination file's * parent directories will be created (if they do not exist already). The * destination file will be overwritten if it already exists. * * @throws IOException */ public static void copyFile(File sourceFile, File destFile) throws IOException { assert sourceFile.exists() && sourceFile.isFile(); destFile.getParentFile().mkdirs(); if (!destFile.getParentFile().exists()) { throw new IOException("Could not make parent directories"); } destFile.createNewFile(); if (!destFile.exists()) { throw new IOException("Could not create destination file"); } FileOutputStream fos = null; FileInputStream fis = null; try { fos = new FileOutputStream(destFile); fis = new FileInputStream(sourceFile); byte[] buf = new byte[4096]; int numRead; while ((numRead = fis.read(buf)) >= 0) { fos.write(buf, 0, numRead); } } finally { try { if (fis != null) { fis.close(); } } finally { if (fos != null) { fos.close(); } } } } }