Copy a File in Java using Apache Commons IO

Tags: FileUtils Apache Commons Apache Commons IO File Copy

In this Java tutorial, we learn how to copy a file to a new location using 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/

How to Copy a File using FileUtils class

The following Java program shows you how to use the method FileUtils.copyFile() to copy a file to a new location.

CopyFile.java

import org.apache.commons.io.FileUtils;

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

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

            FileUtils.copyFile(sourceFile, destinationFile);

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

Happy Coding 😊