How to copy a folder and all its subfolders and files into another folder [duplicate]
How can I copy a folder and all its subfolders and files into another folder?
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);
}
}
}
Apache Commons IO can do the trick for you. Have a look at FileUtils.
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.
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.
精彩评论