In this article, you'll learn how to copy all files and sub-directories from one directory to another directory using Java NIO API as well as Apache Commons IO.
Using Files.copy()
Method
In Java 8 and higher, you can use Files.copy()
combined with Files.walk()
from NIO API to copy all files and sub-directories from one director to another in Java:
try {
// source & destination directories
Path src = Paths.get("dir");
Path dest = Paths.get("dir-new");
// create stream for `src`
Stream<Path> files = Files.walk(src);
// copy all files and folders from `src` to `dest`
files.forEach(file -> {
try {
Files.copy(file, dest.resolve(src.relativize(file)),
StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
e.printStackTrace();
}
});
// close the stream
files.close();
} catch (IOException ex) {
ex.printStackTrace();
}
Using Apache Commons IO
The Apache Commons IO library provides FileUtils.copyDirectory()
method to copy all files and sub-directories from one directory to another directory. Here is an example:
try {
// source & destination directories
File src = new File("dir");
File dest = new File("dir-new");
// copy all files and folders from `src` to `dest`
FileUtils.copyDirectory(src, dest);
} catch (IOException ex) {
ex.printStackTrace();
}
Don't forget to include Apache Commons IO dependency to your Maven's project pom.xml
file:
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
For a Gradle project, add the following dependency to your build.gralde
file:
implementation 'commons-io:commons-io:2.6'
Further Reading
You may be interested in other Java I/O articles:
- Reading and Writing Files in Java
- How to Read and Write Text Files in Java
- How to Read and Write Binary Files in Java
- Reading and Writing Files using Java NIO API
- How to read a file line by line in Java
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.