Here you can find the source of copyDirectory(File source, File target)
Parameter | Description |
---|---|
source | - The source directory/folder. |
target | - THe target directory/ folder. |
Parameter | Description |
---|---|
IOException | - If anything during the operation fails. |
public static boolean copyDirectory(File source, File target) throws IOException
//package com.java2s; //License from project: Open Source License import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class Main { /**//from w w w. ja va2s . co m * Helper function used to copy the directory. * Recursively calls it on all sub files and directories. * * @param source - The source directory/folder. * @param target - THe target directory/ folder. * @return - true or false. * @throws IOException - If anything during the operation fails. */ public static boolean copyDirectory(File source, File target) throws IOException { // check first if source file exists or not if (!source.exists()) { return false; } if (source.isDirectory()) { if (!target.exists()) { target.mkdir(); } File[] listFile = source.listFiles(); for (File f : listFile) { File sourceFile = new File(source, f.getName()); File outputFile = new File(target, f.getName()); if (f.isDirectory()) { copyDirectory(sourceFile, outputFile); } else { copyFile(sourceFile, outputFile); } } } return true; } /** * Helper function to copy the file. * * @param input - The input file. * @param output - The output file to which the input should be copied. * @throws IOException - Any exception thrown during the operation. */ public static void copyFile(File input, File output) throws IOException { FileInputStream inputStream = new FileInputStream(input); // target file declaration FileOutputStream outputStream = new FileOutputStream(output); int lengthStream; byte[] buff = new byte[1024]; while ((lengthStream = inputStream.read(buff)) > 0) { // writing to the target file contents of the source file outputStream.write(buff, 0, lengthStream); } outputStream.close(); inputStream.close(); } }