How to Copy a Directory in Java

In Java, copying directories can be approached in multiple ways, depending on the requirements. Whether you want to copy a single directory or multiple directories, Java's I/O classes have got you covered. Let's delve into different methods for copying directories. 

1. Using Files.copy() for Single Directory (Shallow Copy) 

The Files.copy() method is perfect for copying a single directory without its contents.

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class CopySingleDirectory {
    public static void main(String[] args) {
        Path sourceDir = Paths.get("sourceDirectory");
        Path targetDir = Paths.get("targetDirectory");

        try {
            Files.copy(sourceDir, targetDir);
            System.out.println("Directory copied successfully!");
        } catch (Exception e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

2. Using Files.walkFileTree() for Deep Copy 

For a deep copy (copying directory along with its contents and nested directories), Files.walkFileTree() provides a recursive solution.

import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;

public class DeepCopyDirectory {
    public static void main(String[] args) {
        Path sourcePath = Paths.get("sourceDirectory");
        Path destinationPath = Paths.get("destinationDirectory");

        try {
            Files.walkFileTree(sourcePath, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult preVisitDirectory(final Path dir, final BasicFileAttributes attrs) throws IOException {
                    Files.createDirectories(destinationPath.resolve(sourcePath.relativize(dir)));
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
                    Files.copy(file, destinationPath.resolve(sourcePath.relativize(file)));
                    return FileVisitResult.CONTINUE;
                }
            });
            System.out.println("Directory and its contents copied successfully!");
        } catch (IOException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

3. Using Apache Commons IO for Multiple Directories 

The Apache Commons IO library provides a utility class FileUtils that simplifies many I/O operations, including copying directories. This can be especially useful for bulk directory copying operations.

import org.apache.commons.io.FileUtils;
import java.io.File;

public class ApacheCopyDirectory {
    public static void main(String[] args) {
        File sourceDir1 = new File("sourceDirectory1");
        File sourceDir2 = new File("sourceDirectory2");
        File targetDir = new File("targetDirectory");

        try {
            FileUtils.copyDirectoryToDirectory(sourceDir1, targetDir);
            FileUtils.copyDirectoryToDirectory(sourceDir2, targetDir);
            System.out.println("Directories copied successfully using Apache Commons IO!");
        } catch (Exception e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

Note: Ensure you have added the Apache Commons IO library to your classpath or project dependencies to use FileUtils

Conclusion 

Whether you need a shallow copy of a directory, a deep copy, or need to copy multiple directories, Java provides several methods tailored to specific needs. From native solutions like Files.copy() and Files.walkFileTree() to third-party solutions like Apache Commons IO's FileUtils, Java ensures flexibility and efficiency in handling directory copying operations.

Related Directory Handling Examples

Comments