Copy Content from URL to File in Java using Apache Commons IO
Tags: FileUtils Apache Commons Apache Commons IO File URL Copy
In this Java tutorial we show you how to download and copy contents from a given URL into a File 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/
How to Copy URL to File using FileUtils class
Apache Commons IO library provides the method FileUtils.copyURLToFile() that allows you to copy all bytes of a given URL into a destination File. The following Java example code shows you how to use the method to download contents at https://simplesolution.dev and copy bytes to file at D:\Data\index.html on your local disk.
CopyURLToFile.java
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
public class CopyURLToFile {
public static void main(String... args) {
try {
URL sourceUrl = new URL("https://simplesolution.dev");
File destinationFile = new File("D:\\Data\\index.html");
FileUtils.copyURLToFile(sourceUrl, destinationFile);
System.out.println("Copy URL " + sourceUrl + " to file " + destinationFile + " success!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Copy URL https://simplesolution.dev to file D:\Data\index.html success!
Happy Coding 😊