How can I download files from a URL using HTTP?
Created May 4, 2012
Tim Rohaly
One way to do this is by using a URLConnection to open a stream to your desired URL, then copy the data out of the stream to a file on your local file system. As an example, here's a little snippet of code which lets you download the jGuru logo to your machine:
URL url = new URL("http://www.jguru.com/images/logo.gif"); URLConnection connection = url.openConnection(); InputStream stream = connection.getInputStream(); BufferedInputStream in = new BufferedInputStream(stream); FileOutputStream file = new FileOutputStream("logo.gif"); BufferedOutputStream out = new BufferedOutputStream(file); int i; while ((i = in.read()) != -1) { out.write(i); } out.flush();Note the use of "Stream" classes instead of "Reader" classes. This is done because in general a URL may contain binary data, as in this example. Also note that both the input and the output streams are buffered - this greatly speeds the download time and is far more efficient that reading and writing a single byte at a time, especially over the network.