In this article, we will look at different ways to download and save a file from the Internet in Java.

Using Java NIO API

In Java 7+, the simplest and a pure Java-based solution is using the NIO API (classes in java.nio.* package) to download and save a file from a URL. Here is an example that downloads and saves an image from a URL to a file on the local file system:

try {
    // internet URL
    URL url = new URL("https://i.imgur.com/mtbl1cr.jpg");

    // download and save image
    ReadableByteChannel rbc = Channels.newChannel(url.openStream());
    FileOutputStream fos = new FileOutputStream("cat.jpg");
    fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);

    //close writers
    fos.close();
    rbc.close();

} catch (IOException ex) {
    ex.printStackTrace();
}

The transferFrom() method is by far more efficient than using a simple loop for copying bytes from the source channel to this channel. The third argument in transferFrom() is the maximum number of bytes to transfer. Long.MAX_VALUE will transfer at most 2^63 bytes.

Using InputStream Class

Another JDK-only solution to download and save an Internet file is using the InputStream class. You can use File.openStream() to open an InputStream and then convert it into a file by using Files.copy() method:

try (InputStream in = URI.create("https://i.imgur.com/mtbl1cr.jpg")
        .toURL().openStream()) {

    // download and save image
    Files.copy(in, Paths.get("cat.jpg"));

} catch (IOException ex) {
    ex.printStackTrace();
}

Using Apache Commons IO

The Apache Commons IO library provides FileUtils.copyURLToFile() method to download and save a file from the Internet as shown below:

try {
    // internet URL
    URL url = new URL("https://i.imgur.com/mtbl1cr.jpg");

    // local file path
    File file = new File("cat.jpg");

    // connection and read timeouts
    // TODO: adjust as per your own requirement
    int connectionTimeout = 10 * 1000; // 10 sec
    int readTimeout = 300 * 1000; // 3 min

    // download and save file
    FileUtils.copyURLToFile(url, file, connectionTimeout, readTimeout);

} catch (IOException e) {
    e.printStackTrace();
}

Don't forget to include Apache Commons IO dependency to your Maven's project pom.xml file:

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

For a Gradle project, add the following dependency to your build.gralde file:

implementation 'commons-io:commons-io:2.6'

Further Reading

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

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.