Code to Download File from URL in Java

Below is the code to download the complete contents of a URL to your local hard drive.

//IMPORTS
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.io.File;
METHOD CODE
    private static void download(String url) throws IOException {

        String fileName="Path\to\File.extn";//The file that will be saved on your computer
        
        URL link = new URL(url); //The file that you want to download

        //Code to download
        InputStream in = new BufferedInputStream(link.openStream());
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buf = new byte[2048];
        int n = 0;
        while (-1 != (n = in.read(buf))) {
            out.write(buf, 0, n);
            System.out.print("|");//Progress Indicator
        }
        out.close();
        in.close();
        byte[] response = out.toByteArray();

        FileOutputStream fos = new FileOutputStream(fileName);
        fos.write(response);
        fos.close();
        //End download code
        System.out.println("#");

    }

Note: For large file downloads, the JVM may throw OutOfMemoryError

Leave a Reply