Java — How to copy Directories recursively | Code Factory

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);
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




Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Why Mighty Mutts is unique… the technical answer

Say Hello to the Inu Crew Team!

Caching in the distributed system

centralized cache in distributed system

Progress Bar Python- For Jupyter Notebook

Unleash the power of the Glassfy webhooks

A Complete Guide to Nearshore Software Development Outsourcing

Java — How to compare Date and Time | Code Factory

git flight guide for git travelers

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
Code Factory

Code Factory

More from Medium

Features of Java programming language

Java training in Kochi

Naming Conventions in Java

Java Collections Interview Questions

Annotation in Java..!