Copy a directory with files and subdirectories in Java

August 14, 2020 No comments Java IO File Directory

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.

package com.frontbackend.java.io.copy;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class CopyDirectoryUsingWalk {

    public static void main(String[] args) throws IOException {
        final Path fromPath = Paths.get("/tmp/from");

        Files.walk(fromPath)
             .forEach(source -> copySourceToDest(fromPath, source));
    }

    private static void copySourceToDest(Path fromPath, Path source) {
        Path destination = Paths.get("/tmp/to", source.toString()
                                                      .substring(fromPath.toString()
                                                                         .length()));
        try {
            Files.copy(source, destination);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

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:

├── from
│   ├── dir
│   │   └── third
│   ├── first
│   └── second

After running our first example code the new directory will appear in /tmp directory with the following files and subdirectories:

└── to
    ├── dir
    │   └── third
    ├── first
    └── second

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:

package com.frontbackend.java.io.copy;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class CopyDirectoryUsingRecursion {

    public static void main(String[] args) throws IOException {
        File sourceDir = new File("/tmp/from");
        File destDir = new File("/tmp/to");

        copyDirectory(sourceDir, destDir);
    }

    private static void copyDirectory(File sourceDir, File destDir) throws IOException {
        if (!destDir.exists()) {
            destDir.mkdir();
        }

        for (String f : sourceDir.list()) {
            File source = new File(sourceDir, f);
            File destination = new File(destDir, f);

            if (source.isDirectory()) {
                copyDirectory(source, destination);
            } else {
                copyFile(source, destination);
            }
        }
    }

    private static void copyFile(File sourceFile, File destinationFile) throws IOException {
        FileInputStream input = new FileInputStream(sourceFile);
        FileOutputStream output = new FileOutputStream(destinationFile);

        byte[] buf = new byte[1024];
        int bytesRead;

        while ((bytesRead = input.read(buf)) > 0) {
            output.write(buf, 0, bytesRead);
        }

        input.close();
        output.close();
    }
}

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:

package com.frontbackend.java.io.copy;

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

import org.apache.commons.io.FileUtils;

public class CopyDirectoryUsingFileUtils {

    public static void main(String[] args) throws IOException {
        File sourceDirectory = new File("/tmp/from");
        File destinationDirectory = new File("/tmp/to");

        FileUtils.copyDirectory(sourceDirectory, destinationDirectory);
    }
}

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.

{{ message }}

{{ 'Comments are closed.' | trans }}