Take the 2-minute tour ×

How can I copy a folder and all its subfolders and files into another folder?

share|improve this question
duplicate of stackoverflow.com/questions/5282177/… –  Mat Mar 20 '11 at 13:25

3 Answers 3

up vote 11 down vote accepted

Apache Commons IO can do the trick for you. Have a look at FileUtils.

share|improve this answer
link is down. pls update –  4ndro1d Apr 25 '13 at 9:54

Choose what you like:

  • FileUtils from Apache Commons IO (the easiest and safest way)

Example with FileUtils:

File srcDir = new File("C:/Demo/source");
File destDir = new File("C:/Demo/target");
FileUtils.copyDirectory(srcDir, destDir);

Example with AutoCloseable feature in Java 7:

public void copy(File sourceLocation, File targetLocation) throws IOException {
    if (sourceLocation.isDirectory()) {
        copyDirectory(sourceLocation, targetLocation);
    } else {
        copyFile(sourceLocation, targetLocation);

private void copyDirectory(File source, File target) throws IOException {
    if (!target.exists()) {

    for (String f : source.list()) {
        copy(new File(source, f), new File(target, f));

private void copyFile(File source, File target) throws IOException {        
    try (
            InputStream in = new FileInputStream(source);
            OutputStream out = new FileOutputStream(target)
    ) {
        byte[] buf = new byte[1024];
        int length;
        while ((length = in.read(buf)) > 0) {
            out.write(buf, 0, length);
share|improve this answer
This is working but if an exception happens you won't close the streams : you should add a try catch finally block. –  Tim Sep 14 at 18:41
@Tim, that's true. Fixed –  smas Sep 14 at 20:33

look at java.io.File for a bunch of functions.

you will iterate through the existing structure and mkdir, save etc to achieve deep copy.

share|improve this answer

Your Answer


