Here you can find the source of copyFile(File sourceFile, File targetDir)
public static boolean copyFile(File sourceFile, File targetDir) throws FileNotFoundException, IOException
//package com.java2s; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; public class Main { private static final int DEFAULT_BUFFER_SIZE = 1024 * 4; public static boolean copyFile(File sourceFile, File targetDir) throws FileNotFoundException, IOException { File targetFile = new File(targetDir, sourceFile.getName()); //target file's top file if (sourceFile.isDirectory()) { //Copy directory targetFile.mkdir();//from ww w .j a va2s . co m File[] dir = sourceFile.listFiles(); for (int i = 0; i < dir.length; i++) { if (!copyFile(dir[i], targetFile)) { return false; } } return true; } else { //Copy file FileInputStream fis = new FileInputStream(sourceFile); FileOutputStream fos = new FileOutputStream(targetFile); byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; int c = 0; while ((c = fis.read(buffer)) != -1) { fos.write(buffer, 0, c); } fis.close(); fos.close(); return true; } } public static boolean copyFile(File sourceFile, File targetDir, String targetFilename) throws FileNotFoundException, IOException { File targetFile = new File(targetDir, targetFilename); //target file's top file if (sourceFile.isDirectory()) { //Copy directory return false; } else { //Copy file FileInputStream fis = new FileInputStream(sourceFile); FileOutputStream fos = new FileOutputStream(targetFile); byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; int c = 0; while ((c = fis.read(buffer)) != -1) { fos.write(buffer, 0, c); } fis.close(); fos.close(); return true; } } }