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 use Proxy class to configure HTTP and SOCKS proxies in Java? - March 27, 2025
- How do I retrieve network interface information using NetworkInterface in Java? - March 26, 2025
- How do I work with InetAddress to resolve IP addresses in Java? - March 25, 2025