Copy a Directory in Java

In this tutorial, we will see how to copy a non-empty directory recursively with all its sub-directories and files to another location in Java.

This can be done in many ways as given below.
1). Using java NIO
2). Using the java.io
3). Using third-party libraries.

We will see all of them.

1). Using java NIO

import java.io.IOException; import java.nio.file. * ; public class CopyDirectoryByNIO { public static void main(String[] args) throws IOException { String sourceDir = "/home/download/files"; String destinationDir = "/home/devuser/files"; Path sourceDir = Paths.get(sourceDir); Path destinationDir = Paths.get(destinationDir "); //Traverse the all files in the dir. Files.walk(sourceDir) .forEach(sourcePath -> { try { Path targetPath = destinationDir.resolve(sourceDir.relativize(sourcePath)); System.out.println(" Copying % s to % s % n ", sourcePath, targetPath); Files.copy(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING); System.out.println(" directory copied successfully."); } catch (IOException ex) { System.out.println(ex.getMessage()); } catch (Exception ex) { System.out.println(ex.getMessage()); } }); } }" output:

2). Using the java.io

Its more customized manual steps.Here

we'll create a directory in the destination directory for every directory in the source directory tree.and copy the files using copy a file using FileInputStream and FileOutputStream.

a). List the content of the current directory.

b). For each item in the current directory: If the item is a directory:
- Create the directory in the new location.
- Copy this directory by repeating the steps a, b, and c (At this point the function will call itself, hence the recursion).
If the item is a file, copy the file to the new location.

c). Return if the current directory is empty or if the last item is traversed.

public class CopyDirectoryByCoreJava { // utility method which is exposed to the outside public static void copyDirectory(File sourceDir, File destDir) throws IOException { // checks arguments... // call copyDirectoryImpl() } // implementation of copy directory method private static void copyDirectoryImpl(File sourceDir, File destDir) throws IOException { // implements the recursion algorithm above... // calls copyFile() method } // copy a file private static void copyFile(File sourceFile, File destFile) throws IOException { // code to copy a file to another location } }

import java.io.IOException; import java.nio.file. * ; public class CopyDirectoryByCoreJava { public static void main(String[] args) throws IOException { String sourceDir = "/home/download/files"; String destinationDir = "/home/devuser/files"; File srcFile = new File(sourceDir); File desFile = new File(destinationDir); private static void copyDirectory(File srcFile, File desFile) throws IOException { // throws exception if the source does not exist if (!sourceDir.exists()) { throw new IllegalArgumentException("srcFile does not exist"); } if (!desFile.exists()) { desFile.mkdir(); } for (String f: srcFile.list()) { copyDirectoryImpl(new File(srcFile, f), new File(desFile, f)); } } public static void copyDirectoryImpl(File srcFile, File destFile) throws IOException { if (srcFile.isDirectory()) { copyDirectory(srcFile, destFile); } else { copyFile(srcFile, destFile); } } private static void copyFile(File srcFile, File destFile) throws IOException { try (InputStream in =new FileInputStream(srcFile); OutputStream out = new FileOutputStream(destFile)) { byte[] buf = new byte[1024]; int length; while ((length = in.read(buf)) & gt; 0) { out.write(buf, 0, length); } } }

3). Using third-party libraries

a). Using Apache Commons IO

Apache common Io library provides classes and methods to copy dir.It's pretty easy to use.

we need to include maven dependencies as given below.

<dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.7</version> </dependency>

import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils;; public class CopyDirectoryByApacheCommonsIO { public static void main(String[] args) throws IOException { String sourceDir = "/home/download/files"; String destinationDir = "/home/devuser/files"; File source = new File(sourceDir); File target = new File(destinationDir); FileUtils.copyDirectory(source, target); } }

How to get a folder name from the file path in java?

private void getFolderName() { String name, folder; int pos; name = file.getParent(); //location of file pos = name.indexOf("\\", name.indexOf("\\") + 1); folder = name.substring(name.lastIndexOf("\\")+1,name.length()); System.out.println (""+folder); }

Post/Questions related to Copy a Directory in Java

How to download a pdf file using java?
How to copy a file from one directory to another in java?
How to put a file into a folder in java?
How to create a directory in java?
How to read all files in a directory in java?
How to delete all files in a directory in java?
How to check if directory exists in java?
How to Download File from URL in Java
Read file to byte[] array in Java Java File Reader Examples
Java file writer Example
java.nio.file.Files methods with Examples
Java File Path, Absolute Path, and Relative Path
Path toString() method in Java Create New File in Java

In this article, we have seen Copy a Directory in Java. All source code in the article can be found in the GitHub repository.