Download files with Java

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

Your email address will not be published.

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>

This entry was posted on 05/12/2009 and is filed under JEE/Network. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.