Java — How to copy Directories recursively | Code Factory

Donate : Link

WordPress Blog : Link

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.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
* @author code.factory
public class CopyDirectoryRecursively {
public static void main(String... args) throws IOException {
Path sourceDir = Paths.get("folder/folder1");
Path destinationDir = Paths.get("folder/folder2");
// 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);

Output :

Copying folder\folder1 to folder\folder2
I/O error: java.nio.file.DirectoryNotEmptyException: folder\folder2
Copying folder\folder1\folder1.1 to folder\folder2\folder1.1
Copying folder\folder1\test.txt to folder\folder2\test.txt

Before :

After :



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store