Skip to content

aviyehuda.com

Menu
  • Open Source
  • Android
  • Java
  • Others
  • Contact Me
  • About Me
Menu

Download files with Java

Posted on 05/12/2009

In my many home-brew projects I have found myself using this next piece of code to download files or web pages from the net.

It is very easy and I think it should always be in your reach.

public static void download(String downloadPath, String localFilePath) {
		OutputStream out = null;
		URLConnection conn = null;
		InputStream  in = null;
		try {
			//Connecting to site
		    URL url = new URL(downloadPath);
			conn = url.openConnection();
			in = conn.getInputStream();
			
			out = new BufferedOutputStream(new FileOutputStream(localFilePath));
            
			byte[] buffer = new byte[1024];
			int numRead;
			long numWritten = 0;

			//Reading the file into buffer
			while ((numRead = in.read(buffer)) != -1) {
				out.write(buffer, 0, numRead);
				numWritten += numRead;
			}
		} catch (Exception exception) {
			exception.printStackTrace();
		} finally {
			try {
				if (in != null) {
					in.close();
				}
				if (out != null) {
					out.close();
				}
			} catch (IOException ioe) {
			}
		}
	}

As you can see, really simple and useful.
I’ll probably use it in my next posts.

downloaddownload source

Leave a Reply Cancel reply

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


About Me

REFCARD – Code Gems for Android Developers

Categories

  • Android
  • AWS
  • AWS EMR
  • bluetooth
  • Chrome extension
  • ClientSide
  • Clover
  • Coding Coventions
  • Data Lake
  • General
  • GreaseMonkey
  • Hacks
  • hibernate
  • hibernate validator
  • HTML5
  • HtmlUnit
  • Image Manipulation
  • Java
  • Java Technologies
  • JavaScript
  • Java_Mail
  • JEE/Network
  • Job searching
  • Open Source
  • Pivot
  • projects
  • Pure Java
  • software
  • Spark
  • Trivia
  • Web development

Archives

  • March 2022 (1)
  • January 2022 (1)
  • January 2021 (1)
  • December 2018 (1)
  • August 2018 (1)
  • October 2013 (1)
  • March 2013 (1)
  • January 2013 (2)
  • July 2012 (1)
  • April 2012 (1)
  • March 2012 (1)
  • December 2011 (1)
  • July 2011 (1)
  • June 2011 (1)
  • May 2011 (2)
  • January 2011 (1)
  • December 2010 (1)
  • November 2010 (3)
  • October 2010 (4)
  • July 2010 (1)
  • April 2010 (2)
  • March 2010 (1)
  • February 2010 (2)
  • January 2010 (5)
  • December 2009 (10)
  • September 2009 (1)
 RSS Feed
1d96f52e7159fe09c7a3dd2a9816d166-332
©2023 aviyehuda.com | Design: Newspaperly WordPress Theme