Download a file from a URL and store in a specific directory using Java

In this tutorial, you learn how to download a file from a URL using the Java IO package.

You use the BufferedInputStream class to read the contents of a file, and the BufferedOutputStream and FileOutputStream classes to write the content onto a file on your computer. You use the URL and HttpURLConnection classes to open the file on a specified address, establish a connection, and get the input stream for the BufferedInputStream to read.

Downloading the file from a URL from the internet using Java:

Steps:

  1. Create a URL object using the syntax shown below and pass the link as the parameter.
    URL url = new URL(urlLink);
  2. Create an HTTP URL connection.
    HttpURLConnection http = (HttpURLConnection)url.openConnection();
  3. Get the file size of the file that you want to download.
    double filesize = (double)http.getContentLengthLong();
  4. Get the input stream from the HTTP connection, and create an object from the BufferedInputStream class to read the same.
    BufferedInputStream input = new BufferedInputStream(http.getInputStream());
  5. Save the downloaded file onto your computer in the specified location by using the FileOutputStream Class.
    FileOutputStream ouput = new FileOutputStream(fileLoc);
  6. Create an object of BufferedOutputStream to write the data onto the output file. Pass the object of the FileOutputStream as the first parameter, and pass the length of the output stream buffer, 1024 bytes as the second parameter.
    BufferedOutputStream bufferOut = new BufferedOutputStream(ouput, 1024);
  7. Using a while loop, read the content from the input stream and write it into the output file.
  8. The required file is saved in the specified directory on your computer after the download is completed.

Working of the while loop:

  1. Read the data from the BufferedInputStream object ‘input’ into the buffer variable using the read() method, by setting the offset to 0 and the number of bytes to read as 1024.
    input.read(buffer, 0, 1024);
  2. Write the data stored in the buffer variable onto the output file using the write() method of the BufferedOutputStream class. Set the offset to 0 and the number of bytes to write as readbyte, which is the number of bytes read in the previous step.
    bufferOut.write(buffer,0,readbyte);
  3. Calculate the percentage of the file downloaded/written in each iteration and print it.
    Formula: TotalDownload / filesize
    (where TotalDownload is the total number of bytes written onto the output file after each iteration).
  4. Repeat the preceding steps until the while loop terminates.

Note: The while loop terminates after reaching the end of the input stream, and the number of bytes reads less than zero.

Java Code:

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

public class downloadFIleFromURL {
  
  public void download(String urlLink, File fileLoc) {
    try {
      
      byte[] buffer = new byte[1024];
      double TotalDownload = 0.00;
      int readbyte = 0; //Stores the number of bytes written in each iteration.
      double percentOfDownload = 0.00;
      
      URL url = new URL(urlLink);
      HttpURLConnection http = (HttpURLConnection)url.openConnection();
      double filesize = (double)http.getContentLengthLong();
      
      BufferedInputStream input = new BufferedInputStream(http.getInputStream());
      FileOutputStream ouputfile = new FileOutputStream(fileLoc);
      BufferedOutputStream bufferOut = new BufferedOutputStream(ouputfile, 1024);

      while((readbyte = input.read(buffer, 0, 1024)) >= 0) {
        //Writing the content onto the file.
        bufferOut.write(buffer,0,readbyte);
        //TotalDownload is the total bytes written onto the file.
        TotalDownload += readbyte;
        //Calculating the percentage of download. 
        percentOfDownload = (TotalDownload*100)/filesize;
        //Formatting the percentage up to 2 decimal points.
        String percent = String.format("%.2f", percentOfDownload);
        System.out.println("Downloaded "+ percent + "%");
      }

      System.out.println("Your download is now complete.");
      bufferOut.close();
      input.close();
    }
    catch(IOException e){
      e.printStackTrace();
    }
      
  }
  public static void main(String[] args) {
    
    //Please provide the correct URL of what you want to download, and the correct directory with a name and extension to save the downloaded file in.
    String link = "http://free.epubebooks.net/ebooks/books/harry-potter-book-1.pdf";
    File fileLoc = new File("D:\\MyDownloads\\HarryPotter.pdf");
    
    downloadFIleFromURL d = new downloadFIleFromURL();
    d.download(link, fileLoc);
  }
}

Note: The extension of the downloaded file saved on the computer should be the same as the type of file you are downloading. For example, in the program above, we are downloading a PDF file and hence we save the file with the .pdf extension on the computer.

Output: Download PDF file, JPG file from URL using Java

  1. Downloading a PDF file from the URL provided:
    Provide the required URL, and the directory and file name with its extension to save the file on your computer. Considering the details provided in the above program, the PDF file to be downloaded is shown below:
    Download a file from a URL and store in a specific directory using Java
    The output of the program will be:

    Downloaded 1.07%
    Downloaded 5.27%
    Downloaded 12.19%
    Downloaded 25.94%
    Downloaded 48.66%
    Downloaded 76.65%
    Downloaded 88.55%
    Downloaded 94.79%
    Downloaded 98.89%
    Downloaded 99.96%
    Downloaded 100.00%
    Your download is now complete.

    The downloaded PDF file will be stored in the specified directory, with the specified name.
    Download a file from a URL and store in a specific directory using Java

     

  2. Downloading an image from the URL provided:
    Provide the URL of the image address in the above program, and give the directory, file name, and file extension to save the file on your computer.
    Suppose you want to download the following image:
    download image file from internet in Java
    Provide the download link of the image, and the directory with the file’s name and extension:

    //Providing the required link and location:
    String link = "https://s01.sgp1.cdn.digitaloceanspaces.com/article/161106-qqhmbgohup-1625376034.jpg";
    File fileLoc = new File("D:\\MyDownloads\\RogerFederer.jpg");

    The output of the program will be:

    Downloaded 1.54%
    Downloaded 18.53%
    Downloaded 32.42%
    Downloaded 54.04%
    Downloaded 64.85%
    Downloaded 75.66%
    Downloaded 94.18%
    Downloaded 98.82%
    Downloaded 100.00%
    Your download is now complete.

    The downloaded image will be stored in the specified directory, with the specified name.

This is how you download the file from a URL. Hope this tutorial helped!

Also read: How to Parse JSON from URL in Java

Leave a Reply

Your email address will not be published. Required fields are marked *