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("");

    // 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

} catch (IOException ex) {

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("")
        .toURL().openStream()) {

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

} catch (IOException ex) {

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("");

    // 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) {

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


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.