Here you can find the source of copyFileFolder(final File source, final File dest, final boolean override)
Parameter | Description |
---|---|
source | the source file or folder |
dest | the dest file or folder |
override | if to override if the dest exists. |
Parameter | Description |
---|---|
IOException | if any error occurs. |
public static void copyFileFolder(final File source, final File dest, final boolean override) throws IOException
//package com.java2s; //License from project: Open Source License import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class Main { /** Block size for file copying. */ public static final int BLOCK_SIZE_BYTES = 1024; /**//from ww w .ja v a 2 s .c om * @param source the source file or folder * @param dest the dest file or folder * @param override if to override if the dest exists. * @throws IOException if any error occurs. */ public static void copyFileFolder(final File source, final File dest, final boolean override) throws IOException { if (dest.exists()) { if (!override) { return; } else { deleteFileFolder(dest); } } if (source.isDirectory()) { dest.mkdirs(); final File[] children = source.listFiles(); for (final File child : children) { copyFileFolder(child, new File(dest.getAbsolutePath() + "/" + child.getName()), override); } } else { InputStream in = null; OutputStream out = null; try { in = new FileInputStream(source); out = new FileOutputStream(dest); // Transfer bytes from in to out final byte[] buf = new byte[BLOCK_SIZE_BYTES]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } } } /** * @param f the file or folder to be deleted. * @throws IOException if any error occurs. * */ public static void deleteFileFolder(final File f) throws IOException { if (!f.exists()) { return; } if (f.isDirectory()) { for (final File c : f.listFiles()) { deleteFileFolder(c); } } if (!f.delete()) { throw new FileNotFoundException("Failed to delete file: " + f); } } }