Copy List of Files 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 use the FileUtils class of Apache Commons IO library to copy multiple files to a given directory.
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 List of Files to Directory using FileUtils class
The following example Java code shows you how to copy multiple files to a given directory using the FileUtils.copyToDirectory() method.
CopyListOfFilesToDirectory.java
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class CopyListOfFilesToDirectory {
public static void main(String... args) {
try {
List<File> listOfFiles = new ArrayList<>();
listOfFiles.add(new File("D:\\Data\\data.txt"));
listOfFiles.add(new File("D:\\Data\\data1.txt"));
listOfFiles.add(new File("D:\\Data\\data2.txt"));
File destinationDirectory = new File("D:\\TestData");
FileUtils.copyToDirectory(listOfFiles, destinationDirectory);
System.out.println("Copy List of Files to directory " + destinationDirectory + " success!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Copy List of Files to directory D:\TestData success!
Happy Coding 😊