How can I copy a folder and all its subfolders and files into another folder?
Asked
Active
Viewed 7.8k times
4 Answers
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);
- Manually, example before Java 7 (CHANGE: close streams in the finally-block)
- Manually, Java >=7
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
-
This is working but if an exception happens you won't close the streams : you should add a try catch finally block. – Tim Autin Sep 14 '14 at 18:41
-
@Tim, that's true. Fixed – lukastymo Sep 14 '14 at 20:33
-
1The `copyFile` can be enhanced by using the `Files#copy` method (as it uses native hooks if available). – n247s Jul 30 '18 at 14:47
-
There is an error. It is not working if I want to copy 1 file - because targeLocation should always be a folder, whereas in your code, it is always used as a file in copyFile. – Eugene Kartoyev Aug 10 '18 at 01:31
21
Apache Commons IO can do the trick for you. Have a look at FileUtils.
-
-
1http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileUtils.html#copyFile%28java.io.File,%20java.io.File%29 – Raghunandan May 14 '13 at 05:21
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