How to download a file from URL in Java?

Example code teaches you how you can download a page from website using URLConnection object. Learn how to download a file from web using Java program and then save into a directory.

How to download a file from URL?

If you are looking for example code in Java for downloading and saving a file on your hard disk then this tutorial is for you. You will learn how to write code in Java for downloading a file from URL and then saving the file on your computer.

In this tutorial you will learn how to write a code in Java which takes file URL, local file name and destination directory as argument and then saves the file in destination directory.

This example can be used to download any type of file from URL. It can be text file, image file or simple HTML pages.

Here is the explanation of program:

Program constructs the object of following two classes:

OutputStream outStream = null;
URLConnection uCon = null;

The OutputStream  class is used to write in the file on the disk.

Here in this example URLConnection is used to read the data from the URL resource.

Here is the complete code of the program:

package net.roseindia;


public class DownloadFile {

	final static int size = 1024;

	public void downloadFile(String url, String saveAs, String destDir) {
		OutputStream outStream = null;
		URLConnection uCon = null;

		InputStream is = null;
		try {
			URL urlFile;
			byte[] buf;
			int byteRead, byteWritten = 0;
			urlFile = new URL(url);
			outStream = new BufferedOutputStream(new FileOutputStream(destDir
					+ File.separator + saveAs));

			uCon = urlFile.openConnection();
			is = uCon.getInputStream();
			buf = new byte[size];
			while ((byteRead = != -1) {
				outStream.write(buf, 0, byteRead);
				byteWritten += byteRead;
			System.out.println("Downloaded Successfully.");
			System.out.println("File name:\"" + saveAs + "\"\nNo ofbytes :"
					+ byteWritten);
		} catch (Exception e) {
		} finally {
			try {
			} catch (IOException e) {

	public static void main(String[] args) {
		String fileUrl = 
		String localFileName = "url-file-download-directory.gif";
		String destinationDir = "d:/111";
		DownloadFile testDownloadFile = new DownloadFile();
		testDownloadFile.downloadFile(fileUrl, localFileName, destinationDir);



Above example code downloads the url-file-download-directory.gif from and saves into d:/111 folder.

Read more Java tutorials at

Share on Google+Share on Google+

How to download a file from URL in Java?

Posted on: November 8, 2013 If you enjoyed this post then why not add us on Google+? Add us to your Circles



Discuss: How to download a file from URL?  

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image