How do I save an image from a URL to a file?
Author: Deron Eriksson
Description: This Java tutorial shows how to download an image from a URL and save it to a file.
Tutorial created using: Windows XP || JDK 1.6.0_10 || Eclipse JEE Ganymede SR1 (Eclipse 3.4.1)

Occasionally it can be useful to have the ability to download an image from a URL programmatically and save it as a file. A standard way to do this in JavaSW is to obtain an input stream to read from a URL and then write this to an output stream associated with a file.

The SaveImageFromUrl class demonstrates this technique. It obtains a URL object for an image and then obtains an input stream to this image. It creates an output stream to a file via FileOutputStream. Using standard Java stream handling, the input stream is read in chunks via the while loop, and the bytes are written to the output stream.

package com.cakes;


public class SaveImageFromUrl {

	public static void main(String[] args) throws Exception {
		String imageUrl = "";
		String destinationFile = "image.jpg";

		saveImage(imageUrl, destinationFile);

	public static void saveImage(String imageUrl, String destinationFile) throws IOException {
		URL url = new URL(imageUrl);
		InputStream is = url.openStream();
		OutputStream os = new FileOutputStream(destinationFile);

		byte[] b = new byte[2048];
		int length;

		while ((length = != -1) {
			os.write(b, 0, length);