Register Login

How to Download a File from a URL in Java

Updated Sep 13, 2021

Are you looking to create your very own application that can download any file with a single click? If you want such a feature in your Java application, you are in the right place. Many developers require such file downloading features in their Java application. In this article, you will learn how to download a file using a URL in Java.

What is downloading a file using a URL?

Downloading a file through a Java code using a URL allows the Java application to download a file directly into a local system from a remote repository or any other local storage. This process reads a file from the URL and writes it to a local file. Java offers three different ways to download a file using a URL.

1: Plain Java structure:

If we use Java without using any external library, it takes the file as input and reads those data byte by byte. Now, if we take the byte-by-byte data from an input stream & write the bytes to a file output stream, we can achieve downloading using URL.

Program:

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.IOException;
import java.net.URL;
class Main{
    public static void URLDnldFile(URL urlink, String fileName) throws IOException{
        try (InputStream inp = urlink.openStream();
                BufferedInputStream bis = new BufferedInputStream(inp);
                FileOutputStream fops = new FileOutputStream(fileName)){
 
            byte[] d = new byte[1024];
            int i;
            while ((i = bis.read(d, 0, 1024)) != -1){
                fops.write(d, 0, i);
            }}}
    public static void main(String[] args) throws Exception{
        System.out.println("Call this method when you want your application to have this.");
        //Call the URLDnldFile() method
    }}

Explanation:

Here, we have to import the BufferInputStream, FileInputStream, InputStream, IOException, and java.net.URL. Now, create a Main class with a method URLDnldFile() that throws IO exception. The function uses two parameters, one URL link and the other file name. Create a variable ‘d’ of type byte. The stream of bytes will be read within this method using the while loop.

2: Using Java.IO package:

java.io is the traditional Java package that contains various classes. It has some built-in classes used explicitly for reading &writing to a stream.

Program:

import java.net.URL;
import java.net.URLConnection;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
 
public class Main{
   public static void main(String[] args){
      OutputStream ops = null;
      InputStream ins = null;
      String fileLink = "http://200.156.21.23:8080/karlos/project1.txt";
      String oppath = "G:\\Downloads\\urlfile.txt";
      try {
    	URL url = new URL(fileLink);
        URLConnection connection = url.openConnection();
        ins = connection.getInputStream();
        ops = new FileOutputStream(oppath);
	final byte[] bt = new byte[1024];
	int len;
	while ((len = ins.read(bt)) != -1){
	   ops.write(bt, 0, len);}
      }catch (IOException ex){
	   ex.printStackTrace();
      }finally{
           // close streams
           System.out.println("URL's File downloaded....");   
      }}}

Explanation:

Here, we have to import the URLConnection, FileOutputStream, IOException, InputStream, and OutputStream. Within the main(), create a OutputStream and InputStream object and two string variables to hold the URL link and file location. Within the try block, set the URL and the URLConnection using getInputStream(). The following catch block will handle any input-output exception and execute the printStackTrace(). The finally block (which executes automatically as a mandatory part of the program) will display the message “URL's File downloaded.”

3: Using NIO:

Java NIO (abbreviated as New IO) is an alternative input-output Java API that also comes as a Java package. The NIO acts as an alternative to the standard Java IO and Java Networking API. While using the Java IO library, the streams read the data byte by byte. But in the Java NIO package, data are read as channels and buffers.

Program

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.io.File;

public class Main{
   public static void main(String[] args){
     try{
        String fileLink = "http://200.156.21.23:8080/karlos/project1.txt";
        String oppath = "G:\\Downloads\\urlfile.txt";
	URL link = new URL(fileLink);
        InputStream ins = link.openStream();
        ReadableByteChannel chh = Channels.newChannel(link.openStream());
	FileOutputStream fos = new FileOutputStream(new File(oppath));
	fos.getChannel().transferFrom(chh, 0, Long.MAX_VALUE);
	fos.close();
	chh.close();
     } catch(IOException ex){
          ex.printStackTrace();
     }}}

Explanation:

Here, we have to import the URL, Channels (which is a part of NIO package), FileOutputStream, IOException, InputStream OutputStream, and java.io.File. Now, within the Main class, we have created the main(). Inside the main() and within the try block, we have created two String objects by the name fileLink and oppath where we have defined the URL link and the file location. Then we have created an input stream for the file we want to download. Then, we have to produce a new channel responsible for reading the data from this input stream. Next, we have to create an output stream that will write the file contents after putting it from the channel object. Now, we have to fetch the channel from this output stream & define its contents from the channel. The following catch block will handle any input-output exception and execute the printStackTrace().

4: Using Apache Commons IO:

Apache Commons IO is a utility package of Java that has an org.apache.commons.io.FileUtils class. It comprises a copyURLToFile method that can help program IO operations. This method takes 2 arguments – The first is the java.net.URL object that points to the source file while the second is the java.io.File object pointing to the output file path. Note that both paths should consist filename at the end. The output path should be the file location on your local system from where the file will get downloaded.

Program:

import org.apache.commons.io.FileUtils;
 
public class Main {
   public static void main(String[] args) {
      String fileLink = "http://200.156.21.23:8080/karlos/proj.zip";
      String oppath = "G:\\downloads\\proj.zip";
      FileUtils.copyURLToFile(new URL(fileLink), new File(oppath));
   }
}

You can further append Apache Commons IO dependency in your project.
<!– Maven –>
<dependency>
<groupId> org.apache.commons </groupId>
<artifactId> commons-io </artifactId>
<version> 1.3.2 </version>
</dependency>

// Gradle
compile group: ‘org.apache.commons’, name: ‘commons-io’, version: ‘1.3.2’

Explanation:

First, we have to import apache.commons.io.FileUtils. Within the Main class, we have to create the main() inside which we have to create two String variables to hold the URL link and file location. Now, use the FileUtils.copyURLToFile() method to make the program download a file (from the specified location) using the URL (given). This method is taking two parameters fileLink and oppath, that we have created earlier.

Conclusion:

Among these four techniques, Apache Commons IO is the easiest one. But it increases the program size and reduces speed due to external library inclusion. Method 2, which uses the pre-existing IO package is the fastest, but not the latest approach. New Input-Output (NIO package), as the name suggests, is the latest IO package which is an alternative to the IO package, can also benefit you if you want to perform different and latest I/O operations within your program.


×