To copy a directory with the entire child directories and files we can use a handy method provided by the Apache Commons IO FileUtils.copyDirectory()
. This method accepts two parameters, the source directory and the destination directory. The source directory should be available while if the destination directory doesn’t exist, it will be created.
package org.kodejava.commons.io;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
public class DirectoryCopy {
public static void main(String[] args) {
// An existing directory to copy.
String source = "F:/Temp/source";
File srcDir = new File(source);
// The destination directory to copy to. This directory
// doesn't exist and will be created during the copy
// directory process.
String destination = "F:/Temp/target";
File destDir = new File(destination);
try {
// Copy source directory into destination directory
// including its child directories and files. The
// destination directory will be created if it does
// not exist. This copy processes also preserve the
// date information of the file.
FileUtils.copyDirectory(srcDir, destDir);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Maven Dependencies
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.16.1</version>
</dependency>
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024