# How to copy files from one directory to another in Java

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Dec 15, 2019. Topics: Java.
Canonical URL: https://attacomsian.com/blog/java-copy-files-from-one-directory-to-another

> A short tutorial to learn how to copy all files and sub-directories 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:

```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](https://commons.apache.org/proper/commons-io/) library provides `FileUtils.copyDirectory()` method to copy all files and sub-directories from one directory to another directory. Here is an example:

```java
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:

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

For a [Gradle project](https://attacomsian.com/blog/install-gradle-on-ubuntu), add the following dependency to your `build.gralde` file:

```groovy
implementation 'commons-io:commons-io:2.6'
```

## Further Reading

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

* [Reading and Writing Files in Java](https://attacomsian.com/blog/java-read-write-files)
* [How to Read and Write Text Files in Java](https://attacomsian.com/blog/java-read-write-text-files)
* [How to Read and Write Binary Files in Java](https://attacomsian.com/blog/java-read-write-binary-files)
* [Reading and Writing Files using Java NIO API](https://attacomsian.com/blog/java-read-write-files-nio-api)
* [How to read a file line by line in Java](https://attacomsian.com/blog/how-to-read-a-file-line-by-line-in-java)
