Java Copy Directory

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

1. FileUtils – Apache Commons IO

FileUtils.copyDirectory() Function

FileUtils class provides 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.

Use its any one of the forms:

/*
* srcDir - an existing directory to copy, must not be null
* destDir - the new directory, must not be null
* preserveFileDate - true if the file date of the copy should be the same as the original
*/
copyDirectory(File srcDir, File destDir, boolean preserveFileDate)

/*
* 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 copy all directories and files
* preserveFileDate - true if the file date of the copy should be the same as the original
*/
copyDirectory(File srcDir, File destDir, FileFilter filter, boolean preserveFileDate)

The second 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 define follwoing filters as per requirement:

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

Example 1: Copy only directories

Given Java program copies all the directories (and inner directories) 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);

Example 2: Copy directories and 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.

 
//Create a filter for text files
IOFileFilter txtSuffixFilter = FileFilterUtils.suffixFileFilter(".txt");
IOFileFilter txtFiles = FileFilterUtils.andFileFilter(FileFileFilter.FILE, txtSuffixFilter);

// Create a filter for either directories or ".txt" files
FileFilter JointFilter = FileFilterUtils.orFileFilter(DirectoryFileFilter.DIRECTORY, txtFiles);

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

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

2. Files.copy() with File Walker

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.

Example 3: Deep copy directory recursively

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

package com.howtodoinjava.examples.io;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;

public class DirectoryCopyExample 
{
    public static void main(String[] args) throws IOException 
    {
        //Source directory which you want to copy to new location
        File sourceFolder = new File("c:\\temp");
        
        //Target directory where files should be copied
        File destinationFolder = new File("c:\\tempNew");

        //Call Copy function
        copyFolder(sourceFolder, destinationFolder);
    }

    public  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 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 !!

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

Leave a Comment

HowToDoInJava

A blog about Java and related technologies, the best practices, algorithms, and interview questions.