Java tutorial
//package com.java2s; /* * Portions of this file Copyright 1999-2005 University of Chicago Portions of * this file Copyright 1999-2005 The University of Southern California. This * file or a portion of this file is licensed under the terms of the Globus * Toolkit Public License, found at * http://www.globus.org/toolkit/download/license.html. If you redistribute this * file, with or without modifications, you must include this notice in the * file. */ import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class Main { public static void copyFile(File in, File out) throws IOException { // avoids copying a file to itself if (in.equals(out)) { return; } // ensure the output file location exists out.getCanonicalFile().getParentFile().mkdirs(); BufferedInputStream fis = new BufferedInputStream(new FileInputStream(in)); BufferedOutputStream fos = new BufferedOutputStream(new FileOutputStream(out)); // a temporary buffer to read into byte[] tmpBuffer = new byte[8192]; int len = 0; while ((len = fis.read(tmpBuffer)) != -1) { // add the temp data to the output fos.write(tmpBuffer, 0, len); } // close the input stream fis.close(); // close the output stream fos.flush(); fos.close(); } }