03
Mar
2021

How to copy Directories recursively in Java

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/project/Desktop/new-media");
        Path destinationDir = Paths.get("/Users/project/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);
                    }
                });
    }
}
Share

Yaniv Levy

Yaniv Levy, Entrepreneur, visioner & technology passionate with over 20 years on vast experience as a Senior Software Engineer and a Software Architect.

You may also like...