How to download and save a file from Internet in Java
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 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:
The 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 is the maximum number of bytes to transfer. will transfer at most 2^63 bytes.
Using Class
Another JDK-only solution to download and save an Internet file is using the class. You can use to open an and then convert it into a file by using method:
Using Apache Commons IO
The Apache Commons IO library provides method to download and save a file from the Internet as shown below:
Don't forget to include Apache Commons IO dependency to your Maven's project file:
For a Gradle project, add the following dependency to your file:
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.
Last Updated:
-
-
-