HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Java / I/O / Java Copy Directory

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

Share this:

  • Twitter
  • Facebook
  • LinkedIn
  • Reddit

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Comments are closed on this article!

Search Tutorials

Java IO

  • Java IO Introduction
  • Java How IO works?
  • Java IO vs NIO
  • Java Create File
  • Java Write to File
  • Java Append to File
  • Java Read File
  • Java Read File to String
  • Java Read File to Byte[]
  • Java Make File Read Only
  • Java Copy File
  • Java Copy Directory
  • Java Delete Directory
  • Java Current Working Directory
  • Java Read/Write Properties File
  • Java Read File from Resources
  • Java Read File from Classpath
  • Java Read/Write UTF-8 Data
  • Java Check if File Exist
  • Java Create Temporary File
  • Java Write to Temporary File
  • Java Delete Temporary File
  • Java Read from Console
  • Java Typesafe input using Scanner
  • Java Password Protected Zip
  • Java Unzip with Subdirectories
  • Java Generate SHA/MD5
  • Java Read CSV File
  • Java InputStream to String
  • Java String to InputStream
  • Java OutputStream to InputStream
  • Java InputStreamReader
  • Java BufferedReader
  • Java FileReader
  • Java LineNumberReader
  • Java StringReader
  • Java FileWriter
  • Java BufferedWriter
  • Java FilenameFilter
  • Java FileFilter

Java Tutorial

  • Java Introduction
  • Java Keywords
  • Java Flow Control
  • Java OOP
  • Java Inner Class
  • Java String
  • Java Enum
  • Java Collections
  • Java ArrayList
  • Java HashMap
  • Java Array
  • Java Sort
  • Java Clone
  • Java Date Time
  • Java Concurrency
  • Java Generics
  • Java Serialization
  • Java Input Output
  • Java New I/O
  • Java Exceptions
  • Java Annotations
  • Java Reflection
  • Java Garbage collection
  • Java JDBC
  • Java Security
  • Java Regex
  • Java Servlets
  • Java XML
  • Java Puzzles
  • Java Examples
  • Java Libraries
  • Java Resources
  • Java 14
  • Java 12
  • Java 11
  • Java 10
  • Java 9
  • Java 8
  • Java 7

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Java 15 New Features
  • Sealed Classes and Interfaces
  • EdDSA (Ed25519 / Ed448)