This post will discuss how to download a file from a URL in Java.

There are several ways to download a file from a URL in Java. This post provides an overview of some of the available alternatives to accomplish this.

1. Using FileChannel.transferFrom() method

java.nio.channels.FileChannel class in Java provides several methods for reading, writing, mapping, and manipulating a file. It is transferFrom() method transfers bytes into this channel’s file from the given readable byte channel. It accepts three parameters – the source channel, the position within the file at which the transfer is to begin, and the maximum number of bytes to be transferred.

The complete usage is demonstrated below with Java 7 try-with-resource, which take care of closing the opened streams and channels:

Download Code

2. Using Files.copy() method

From Java 7 onward, we can use the java.nio.file.Files.copy() method to copy all bytes from an input stream to a file. It accepts the input stream to read from and the path to the file. Additionally, we can specify how the copying should be done. This is demonstrated below using the try-with-resource block:

Download Code

3. Plain Java

In plain Java, we can read the file byte by byte from the input stream and write the bytes to a file output stream. This would translate to a simple code below:

Download Code

4. Using Apache Commons IO

We can also use Apache Commons IO library, whose FileUtils class offers handy file manipulation utilities. FileUtils’s copyURLToFile() method can be used to copy bytes from the URL source to the specified file destination. It is recommended to use its overloaded version with connection and read timeout parameters.

Download Code

That’s all about downloading a file from a URL in Java.