18

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

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
user496949
  • 83,087
  • 147
  • 309
  • 426

4 Answers4

52

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()) {
        target.mkdir();
    }

    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);
        }
    }
}
lukastymo
  • 26,145
  • 14
  • 53
  • 66
21

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

pdem
  • 3,880
  • 1
  • 24
  • 38
Yaba
  • 5,979
  • 8
  • 38
  • 44
2

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.

Randy
  • 16,480
  • 1
  • 37
  • 55
0

JAVA NIO will help to you to solve your problem. Please have a look on this http://tutorials.jenkov.com/java-nio/files.html#overwriting-existing-files.

yk2
  • 49
  • 1
  • 12