1. Introduction
In this article, we will present how to copy a directory in Java with all files and subdirectories. We are going to use plain Java and external library Apache Commons IO.
2. Copy directory using Java 7
Let's start with the approach available in plain Java using IO libraries.
Java from version 7 provided Paths
and many useful features to manipulate files and directories.
In this example, we used the Files.walk(...)
method available in java.nio
package. We walked through the file tree starting from the root - source directory. Then we used Files.copy(...)
to copy files and directories that we found on the way.
Assume we have the following folder structure:
After running our first example code the new directory will appear in /tmp
directory with the following files and subdirectories:
3. Copy directory using java.io
API (recursion)
In older java.io
API we don't have a dedicated method to walk through a directory tree, so we need to use recursion to list files with directories and subdirectories.
Let's check out this approach:
In this example, we implemented two methods: copyDirectory
and copyFile
. The first method will be called recursively for every folder we found in the tree. We started with the root source and destination folders and run copyDirectory(sourceDir, destDir)
method.
In copyDirectory(...)
method we list all resources and check is it a file or directory. If the resource is a directory we called again copyDirectory(...)
method. In case we found a file we use copyFile(...)
to copy file from one path to another.
4. Copy directory using Apache Commons IO
library
The Apache Commons IO
library comes with many utility classes and methods for manipulating files.
In the following example we used FileUtils
class that provide methods for reading, writing, and copying files:
This approach allows us to create a single-line solution.
5. Conclusion
This article presented how to copy a directory with files and subdirectories in Java. We used plain Java methods available in java.io
and newer java.nio
API and one of the third-party libraries for manipulating files: Apache Commons IO
.
Example snippets used in this tutorial are available over on GitHub.
More Java I/O related articles are available here.
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}