How To Download a File in Java

Here is a snippet that shows how to download a file in java. The snippet is tested and works just fine:

	static public void download(String address, String localFileName) 
											throws MalformedURLException
												 , FileNotFoundException
												 , IOException

		URL url = new URL(address);
		OutputStream out = new BufferedOutputStream(
								new FileOutputStream(localFileName));
		URLConnection conn = url.openConnection();
		InputStream in = conn.getInputStream();

		byte[] buffer = new byte[1024];
		int numRead;
		int progress = 0;
		while ((numRead = != -1) {
			out.write(buffer, 0, numRead);
			progress += 1024;
			System.out.print("\r" + (int)(progress / 1000)+ "kb");


Did you enjoy this tutorial? Be sure to subscribe to the my RSS feed not to miss my new posts!
... or make it popular on

Leave a Comment.