In this article, you’ll learn how to copy a non-empty directory recursively with all its sub-directories and files to another location in Java.

Java copy directory recursively

import java.io.IOException;
import java.nio.file.*;

public class CopyDirectoryRecursively {
    public static void main(String[] args) throws IOException {
        Path sourceDir = Paths.get( "/Users/callicoder/Desktop/new-media");
        Path destinationDir = Paths.get("/Users/callicoder/Desktop/media");

        // Traverse the file tree and copy each file/directory.
        Files.walk(sourceDir)
                .forEach(sourcePath -> {
                    try {
                        Path targetPath = destinationDir.resolve(sourceDir.relativize(sourcePath));
                        System.out.printf("Copying %s to %s%n", sourcePath, targetPath);
                        Files.copy(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING);
                    } catch (IOException ex) {
                        System.out.format("I/O error: %s%n", ex);
                    }
                });
    }
}