Copy a directory in Java
This post will discuss how to copy the contents of a directory to another directory in Java.
Copying a directory includes copying all its files and subdirectories, to a new location. This can be useful for backup, synchronization, or migration purposes. There are several ways to copy a directory and all its child directories and files to a destination in plain Java and using third-party libraries. These are discussed below in detail:
1. Using Java NIO package
Java NIO provides a simple and convenient way to copy a directory in Java using the java.nio.file.Files.copy() method, which takes two Path objects, representing the source and the destination of the copy operation. It also takes an optional CopyOption argument to specify how the copying should be performed, such as replacing existing files or directories, preserving file attributes, or copying symbolic links. By default, copying fails if the target file already exists, unless the REPLACE_EXISTING option is specified.
In Java 8, we can use the Files.walk(…) method to traverse the source directory tree and get a Stream of Path objects representing all the files and directories in it. Then we can copy each file to the target directory using the Files.copy(…) method.
The following code shows how to use the Files.walk(…) with Files.copy(…) method to recursively copy everything in the specified directory into the specified destination. This will only work if the destination directory does not exist or is empty. If the destination directory is not empty, then DirectoryNotEmptyException is thrown.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.util.stream.Stream; class Main { public static void copyDir(Path src, Path dest) throws IOException { try (Stream<Path> stream = Files.walk(src)) { // Iterate over each Path object in the stream stream.forEach(source -> { // Get the relative path from the source directory Path relativePath = src.relativize(source); // Get the corresponding path in the destination directory Path destination = dest.resolve(relativePath); try { // Copy each Path object from source to destination Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { e.printStackTrace(); } }); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { File from = new File("/var/www/html/"); File to = new File("/var/www/html.bak/"); try { copyDir(from.toPath(), to.toPath()); System.out.println("Successfully copied directory."); } catch (IOException ex) { ex.printStackTrace(); } } } |
Instead of using the Files.walk(…) method, we can also use the Files.walkFileTree(…) method to walk a file tree. It requires only a starting point and an instance of FileVisitor to invoke for each file. This option works in Java 7.
2. Using Apache Commons IO
Another option is to use the Apache Commons IO library for copying a directory in Java. We can use the org.apache.commons.io.FileUtils.copyDirectory(…) method, which takes two File objects as arguments, representing the source and the destination of the copy operation, and copies everything from the source directory to another directory. It can also take an optional FileFilter argument to specify which files or directories should be copied or skipped.
Here is an example of using the FileUtils.copyDirectory() method to copy the source directory to the destination directory, optionally passing a FileFilter object as an argument. Unlike previous approach, if the destination directory exists, then this method merges the source with the destination, with the source taking precedence.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
import org.apache.commons.io.FileUtils; import java.io.File; import java.io.IOException; class Main { public static void main(String[] args) { // Create File objects from source and destination directory paths File from = new File("/var/www/html/"); File to = new File("/var/www/html.bak/"); try { // Copy the source directory to the destination directory FileUtils.copyDirectory(from, to); System.out.println("Successfully copied directory."); } catch (IOException ex) { ex.printStackTrace(); } } } |
The advantage of using this method is that it is very convenient to use. It also supports various file filters, such as name filters, size filters, or date filters. However, it requires adding an external dependency to the application, which may increase its size or complexity.
That’s all about copying contents of a directory to another directory in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)