Java — How to copy Directories recursively | Code Factory

Code Factory
1 min readJul 20, 2020

--

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

package com.example.java.programming.file;import java.io.IOException;
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 :

--

--