Here you can find the source of copyFile(String source, String target)
public static boolean copyFile(String source, String target)
//package com.java2s; //License from project: Apache License import java.io.*; public class Main { public static boolean copyFile(String source, String target) { boolean isSuc = false; InputStream in = null;//w w w.ja va 2s. c o m FileOutputStream out = null; try { int bytesum = 0; int byteread = 0; File oldfile = new File(source); newFile(target); if (oldfile.exists()) { in = new FileInputStream(source); out = new FileOutputStream(target, false);// no append, // overwrite old. byte[] buffer = new byte[4096]; while ((byteread = in.read(buffer)) != -1) { bytesum += byteread; out.write(buffer, 0, byteread); } isSuc = true; } else { System.err.println("File " + source + " not exists"); } } catch (Exception e) { System.err.println("Exception occur when copying a file"); e.printStackTrace(); } finally { try { if (in != null) { in.close(); } } catch (IOException e) { } try { if (out != null) { out.close(); } } catch (IOException e) { } } return isSuc; } public static boolean copyFile(InputStream inputStream, String target) { boolean isSuc = false; FileOutputStream out = null; try { int bytesum = 0; int byteread = 0; newFile(target); out = new FileOutputStream(target, false); byte[] buffer = new byte[4096]; while ((byteread = inputStream.read(buffer)) != -1) { bytesum += byteread; out.write(buffer, 0, byteread); } isSuc = true; } catch (Exception e) { System.err.println("Exception occur when copying a file"); e.printStackTrace(); } finally { try { if (inputStream != null) { inputStream.close(); } } catch (IOException e) { } try { if (out != null) { out.close(); } } catch (IOException e) { } } return isSuc; } public static boolean newFile(String fullName) { try { File file = new File(fullName); if (!file.exists()) { if (!file.getParentFile().exists()) { file.getParentFile().mkdirs(); } file.createNewFile(); } } catch (Exception e) { System.out.println("error occur when creating folder"); e.printStackTrace(); return false; } return true; } public static boolean newFile(String fullName, String text) { try { newFile(fullName); FileWriter out = new FileWriter(fullName, false); out.write(text); out.close(); } catch (Exception e) { System.out.println("error occur when creating file"); e.printStackTrace(); return false; } return true; } public static void createNewFile(File f) throws IOException { if (f.exists()) { f.delete(); } f.getParentFile().mkdirs(); f.createNewFile(); } }