Here you can find the source of copyFile(File srcFile, File destFile)
Parameter | Description |
---|---|
srcFile | the validated source file, must not be <code>null</code> |
destFile | the validated destination file, must not be <code>null</code> |
Parameter | Description |
---|---|
IOException | if an error occurs |
public static void copyFile(File srcFile, File destFile) throws IOException
//package com.java2s; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class Main { /**/*w w w.j a v a 2s.c o m*/ * The default buffer size to use. */ private static final int DEFAULT_BUFFER_SIZE = 1024 * 4; /** * Copy a file preserving the date. * * @param srcFile the validated source file, must not be <code>null</code> * @param destFile the validated destination file, must not be <code>null</code> * @throws IOException if an error occurs */ public static void copyFile(File srcFile, File destFile) throws IOException { if (destFile.exists() && destFile.isDirectory()) { throw new IOException("Destination '" + destFile + "' exists but is a directory"); } FileInputStream input = new FileInputStream(srcFile); try { FileOutputStream output = new FileOutputStream(destFile); try { copy(input, output); } finally { close(output); } } finally { close(input); } if (srcFile.length() != destFile.length()) { throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"); } destFile.setLastModified(srcFile.lastModified()); } /** * Copy bytes from an <code>InputStream</code> to an * <code>OutputStream</code>. * * @param input the <code>InputStream</code> to read from * @param output the <code>OutputStream</code> to write to * @return the number of bytes copied * @throws NullPointerException if the input or output is null * @throws IOException if an I/O error occurs * @throws ArithmeticException if the byte count is too large */ public static int copy(InputStream input, OutputStream output) throws IOException { byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; long count = 0; int n = 0; while (-1 != (n = input.read(buffer))) { output.write(buffer, 0, n); count += n; } if (count > Integer.MAX_VALUE) { return -1; } return (int) count; } /** * Close an <code>InputStream</code> ignoring exceptions. * @param input the InputStream to close, may be null or already closed */ public static void close(InputStream input) { try { if (input != null) { input.close(); } } catch (IOException ioe) { // ignore } } /** * Close an <code>OutputStream</code> ignoring exceptions. * @param output the OutputStream to close, may be null or already closed */ public static void close(OutputStream output) { try { if (output != null) { output.close(); } } catch (IOException ioe) { // ignore } } }