Copy Directory to Directory in Java using Apache Commons IO

Tags: FileUtils Apache Commons Apache Commons IO File Directory Copy

In this Java tutorial, we learn how to copy a whole directory to another directory using the FileUtils class of Apache Commons IO library.

How to add Apache Commons IO library to your Java project

To use the Apache Commons IO library in the Gradle build project, add the following dependency into the build.gradle file.

implementation 'commons-io:commons-io:2.8.0'

To use the Apache Commons IO library in the Maven build project, add the following dependency into the pom.xml file.

<dependency>
  <groupId>commons-io</groupId>
  <artifactId>commons-io</artifactId>
  <version>2.8.0</version>
</dependency>

To have more information about the Apache Commons IO library you can visit the library home page at commons.apache.org/proper/commons-io/

How to Copy Directory to Directory using FileUtils class

For example we have source directory at D:\Data1 and destination directory at D:\Data, the Java program below will show you how to copy all child directories and files of source to destination directory.

CopyDirectory.java

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;

public class CopyDirectory {
    public static void main(String... args) {
        try {
            File sourceDirectory = new File("D:\\Data1");
            File destinationDirectory = new File("D:\\Data");

            FileUtils.copyDirectory(sourceDirectory, destinationDirectory);

            System.out.println("Copy directory " + sourceDirectory + " to directory " + destinationDirectory + " success!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
The output is:
Copy directory D:\Data1 to directory D:\Data success!

Happy Coding 😊