Here you can find the source of copyFile(final File fromFile, final File toFile)
Parameter | Description |
---|---|
fromFile | the File to copy (readable, non-null file) |
toFile | the File to copy to (non-null, parent dir exists) |
Parameter | Description |
---|---|
IOException | an exception |
public static void copyFile(final File fromFile, final File toFile) throws IOException
//package com.java2s; //License from project: Apache License 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 { /**//ww w . j av a2 s. c o m * Buffer to use */ public static final int BUFFER_SIZE = 8192; /** * Copy file to file. * * @param fromFile * the File to copy (readable, non-null file) * @param toFile * the File to copy to (non-null, parent dir exists) * @throws IOException */ public static void copyFile(final File fromFile, final File toFile) throws IOException { FileInputStream in = null; FileOutputStream out = null; try { in = new FileInputStream(fromFile); out = new FileOutputStream(toFile); streamToStream(in, out); } finally { if (out != null) { out.close(); } if (in != null) { in.close(); } } } /** * Take a stream to another stream (AND CLOSE BOTH). * * @param inputStream * to read and close * @param outputStream * to (over)write and close */ public static void streamToStream(final InputStream inputStream, final OutputStream outputStream) { streamToStream(inputStream, outputStream, true); } /** * Take a stream to another stream. * * @param inputStream * to read * @param outputStream * to (over)write * @param close * or not */ public static long streamToStream(final InputStream inputStream, final OutputStream outputStream, final boolean close) { long bytesWritten = 0; try { final byte[] buffer = new byte[BUFFER_SIZE]; int len; while ((len = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, len); bytesWritten += len; } if (close) { outputStream.close(); inputStream.close(); } return bytesWritten; } catch (final IOException ioEx) { // Wrap it throw new RuntimeException(ioEx); } } public static void close(final OutputStream outputStream) { try { if (outputStream != null) { outputStream.close(); } } catch (final Exception ex) { throw new RuntimeException(ex); } } public static void close(final InputStream inputStream) { try { if (inputStream != null) { inputStream.close(); } } catch (final Exception ex) { throw new RuntimeException(ex); } } }