Java download file

Today we are going to show you how to download file from the Internet using Java. Our sample program downloads files to a specified destination directory.

Java download file - destination directory

Java download file – destination directory

Java Download File sample program

Our download method takes file location specified as the URL and local destination folder to download file to as arguments. Destination file name is taken from the URL as the last part of the URL String that comes after the “/” sign. Here is our code.



public class JavaDownloadFile {

	public static void main(String[] args) {
		try {
			JavaDownloadFile downloader = new JavaDownloadFile();"", "D:\\tmp");"", "D:\\tmp");"", "D:\\tmp");"", "D:\\tmp");"", "D:\\tmp");"", "D:\\tmp");"", "D:\\tmp");"", "D:\\tmp");"", "D:\\tmp");"", "D:\\tmp");
		} catch (IOException e) {
	 * Method downloads file from URL to a given directory.
	 * @param fileURL	- 	file URL to download
	 * @param destinationDirectory	- directory to download file to
	 * @throws IOException
	private void download(String fileURL, String destinationDirectory) throws IOException {
		// File name that is being downloaded
		String downloadedFileName = fileURL.substring(fileURL.lastIndexOf("/")+1);
		// Open connection to the file
        URL url = new URL(fileURL);
        InputStream is = url.openStream();
        // Stream to the destionation file
        FileOutputStream fos = new FileOutputStream(destinationDirectory + "/" + downloadedFileName);
        // Read bytes from URL to the local file
        byte[] buffer = new byte[4096];
        int bytesRead = 0;
        System.out.print("Downloading " + downloadedFileName);
        while ((bytesRead = != -1) {
        	System.out.print(".");	// Progress bar :)
        // Close destination stream
        // Close URL stream

Check out our ealier post where we are speeding up a downloader program by using Threads in Java – How to speed up applications using threads in java

Download this sample code here.

This code is available on our GitHub repository as well.

2 Responses to "Java download file"

  1. Eyal says:

    Hey thanks for the example,
    I tried it and it only download ~25k of the whole file and put it as a *.tmp file.
    Do you know why?

  2. Balaji says:

    Thank you, this is just what I was looking for


Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

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


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>