Copying a Directory in Java

Learn to copy a directory into a new location in Java. We will see examples for copying only the directories, as well as, deep copying the directory (all sub-folders and all files).

1. Using Apache Commons IO’s FileUtils

1.1. FileUtils.copyDirectory()

FileUtils class provides a clean way for copying files and directories. It provides copyDirectory() method.

  • copyDirectory() copies the contents of the specified source directory to the specified destination directory.
  • The destination directory is created if it does not exist.
  • If the destination directory did exist, then this method merges the source with the destination.

The copyDirectory() is an overloaded method with the following parameters:

  • srcDir : an existing directory to copy, must not be null.
  • destDir : the new directory, must not be null.
  • filter : the filter to apply, null means copying all directories and files.
  • preserveFileDate : true if the last modified date of the copy should be the same as the original.
copyDirectory(File srcDir, File destDir, boolean preserveFileDate)

copyDirectory(File srcDir, File destDir, FileFilter filter, boolean preserveFileDate)

1.2 FileFilter and IOFileFilter

The second version of the method helps in copying only a filtered list of files. For example, if we want to copy only log files from one directory to another directory, we can use the FileFilter class.

We can also use the following builtin filters as per requirement:

  • DirectoryFileFilter.DIRECTORY – it accepts files that are directories.
  • FileFileFilter.FILE – it accepts files that are files (not directories).

Additionally, we can define our own custom filters as explained in this article.

The IOFileFilter helps in building the complex filters by chaining them with and() and or() methods. For example, the given complexFilter will help in copying all files that are either directories or text files.

IOFileFilter txtFileFilter = FileFilterUtils.suffixFileFilter(".txt");

IOFileFilter complexFilter =
        DirectoryFileFilter.DIRECTORY.or(txtFileFilter);

1.3. Java Program to Copy Only the Directory Structure

Given Java program copies all the directories (and subdirectories) from the source location to the destination location. No file is copied at any level.

File srcDir = new File("c:\\temp");
File destDir = new File("c:\\tempNew");

FileUtils.copyDirectory(srcDir, destDir, DirectoryFileFilter.DIRECTORY, false);

1.4. Java Program to Copy Subdirectories and only Text Files

Given Java program copies all the directories (and inner directories) from the source location to the destination location. It also searches and copies all the text files in any of the directories.

IOFileFilter txtFileFilter = FileFilterUtils.suffixFileFilter(".txt");

IOFileFilter complexFilter =
    DirectoryFileFilter.DIRECTORY.or(txtFileFilter);

FileUtils.copyDirectory(srcDir, destDir, complexFilter, true);

1.5. Java Program to Copy All Subdirectories and Files

Do not include any filter if we want to deep copy all subdirectories and files.

FileUtils.copyDirectory(srcDir, destDir, true);

2. Copying Files Recursively using NIO

To deep copy a directory from one location to another with all its sub-folders and multiple files in them, Java does not provide a straightforward API.

We need to use java.nio.file.Files class. Its methods walkFileTree() and copy() must be used together to build a solution for deep copying a directory in Java using native APIs.

Java program for copying all the subdirectories and files c:\temp to a new location c:\tempNew.

File srcDir = new File("c:\\temp");
File destDir = new File("c:\\tempNew");

copyFolder(srcDir.toPath(), destDir.toPath());

//Copy methods
public static void copyFolder(Path src, Path dest) throws IOException {
	try (Stream<Path> stream = Files.walk(src)) {
	  stream.forEach(source -> copy(source, dest.resolve(src.relativize(source))));
	}
}

private static void copy(Path source, Path dest) {
	try {
	  Files.copy(source, dest, StandardCopyOption.REPLACE_EXISTING);
	} catch (Exception e) {
	  throw new RuntimeException(e.getMessage(), e);
	}
}

In the above Java program:

  • If the target directory exists, the system will throw FileAlreadyExistsException.
  • StandardCopyOption.REPLACE_EXISTING will replace the file with the new file if a file already exists in the destination folder. If we do not use this option, the copy will fail if the target file exists.

Verify that files are correctly copied or not. Feel free to modify the code and use it the way you like.

Happy Learning !!

Source Code on Github

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode