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.