How to copy files from one directory to another in Java

In this article, you'll learn how to copy all files and sub-directories from one directory to another directory using Java NIO API as well as Apache Commons IO.

Using Files.copy() Method

In Java 8 and higher, you can use Files.copy() combined with Files.walk() from NIO API to copy all files and sub-directories from one director to another in Java:

try {
    // source & destination directories
    Path src = Paths.get("dir");
    Path dest = Paths.get("dir-new");

    // create stream for `src`
    Stream<Path> files = Files.walk(src);

    // copy all files and folders from `src` to `dest`
    files.forEach(file -> {
        try {
            Files.copy(file, dest.resolve(src.relativize(file)),
                    StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            e.printStackTrace();
        }
    });

    // close the stream
    files.close();

} catch (IOException ex) {
    ex.printStackTrace();
}

Using Apache Commons IO

The Apache Commons IO library provides FileUtils.copyDirectory() method to copy all files and sub-directories from one directory to another directory. Here is an example:

try {
    // source & destination directories
    File src = new File("dir");
    File dest = new File("dir-new");

    // copy all files and folders from `src` to `dest`
    FileUtils.copyDirectory(src, dest);
        
} catch (IOException ex) {
    ex.printStackTrace();
}

Don't forget to include Apache Commons IO dependency to your Maven's project pom.xml file:

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

For a Gradle project, add the following dependency to your build.gralde file:

implementation 'commons-io:commons-io:2.6'

Further Reading

You may be interested in other Java I/O articles:

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.