Here you can find the source of copyFile(File source, File target)
public static long copyFile(File source, File target) throws IOException
//package com.java2s; /*/*from ww w . j av a 2 s . c o m*/ * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 * * 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.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; public class Main { public static long copyFile(File source, File target) throws IOException { long total = 0; FileInputStream fis = null; OutputStream fos = null; try { fis = new FileInputStream(source); mkdirs(target.getParentFile()); fos = new BufferedOutputStream(new FileOutputStream(target)); for (byte[] buffer = new byte[1024 * 32];;) { int bytes = fis.read(buffer); if (bytes < 0) { break; } fos.write(buffer, 0, bytes); total += bytes; } fos.close(); fos = null; fis.close(); fis = null; } finally { try { if (fos != null) { fos.close(); } } catch (final IOException e) { // Suppressed due to an exception already thrown in the try block. } finally { try { if (fis != null) { fis.close(); } } catch (final IOException e) { // Suppressed due to an exception already thrown in the try block. } } } return total; } public static boolean mkdirs(File directory) { if (directory == null) { return false; } if (directory.exists()) { return false; } if (directory.mkdir()) { return true; } File canonDir = null; try { canonDir = directory.getCanonicalFile(); } catch (IOException e) { return false; } File parentDir = canonDir.getParentFile(); return (parentDir != null && (mkdirs(parentDir) || parentDir.exists()) && canonDir.mkdir()); } }