Copy a File to Directory in Java using Apache Commons IO

Tags: FileUtils Apache Commons Apache Commons IO File Directory Copy

In this Java tutorial, we learn how to copy a file to a specified directory using the FileUtils class of Apache Commons IO library.

How to add Apache Commons IO library to your Java project

To use the Apache Commons IO library in the Gradle build project, add the following dependency into the build.gradle file.

implementation 'commons-io:commons-io:2.8.0'

To use the Apache Commons IO library in the Maven build project, add the following dependency into the pom.xml file.

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

To have more information about the Apache Commons IO library you can visit the library home page at commons.apache.org/proper/commons-io/

Copy a File to Directory using FileUtils.copyFileToDirectory()

Apache Commons IO library provides the FileUtils.copyFileToDirectory() method to allow copying a file to a given directory as the Java program below.

CopyFileToDirectory1.java

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;

public class CopyFileToDirectory1 {
    public static void main(String... args) {
        try {
            File sourceFile = new File("D:\\Data1\\test.docx");
            File destinationDirectory = new File("D:\\Data");

            FileUtils.copyFileToDirectory(sourceFile, destinationDirectory);

            System.out.println("Copy file " + sourceFile + " to directory " + destinationDirectory + " success!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
The output is:
Copy file D:\Data1\test.docx to directory D:\Data success!

Copy File to Directory using FileUtils.copyToDirectory()

You also can use the method FileUtils.copyToDirectory() which returns the same result.

CopyFileToDirectory2.java

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;

public class CopyFileToDirectory2 {
    public static void main(String... args) {
        try {
            File sourceFile = new File("D:\\Data1\\test.docx");
            File destinationDirectory = new File("D:\\Data");

            FileUtils.copyToDirectory(sourceFile, destinationDirectory);

            System.out.println("Copy file " + sourceFile + " to directory " + destinationDirectory + " success!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
The output is:
Copy file D:\Data1\test.docx to directory D:\Data success!

Happy Coding 😊