How do I copy directory with all its contents to another directory?

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.14.0</version>
</dependency>

Maven Central

Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.