Download Image from URL in Java

Given the URL of an image, you can download it by using the following Java code.

It download the image and save the image using the original file name. The key is to use InputStream to read image and use OutputStream to write to a file.

public static void saveImage(String imageUrl) throws IOException {
	URL url = new URL(imageUrl);
	String fileName = url.getFile();
	String destName = "./figures" + fileName.substring(fileName.lastIndexOf("/"));
	System.out.println(destName);
 
	InputStream is = url.openStream();
	OutputStream os = new FileOutputStream(destName);
 
	byte[] b = new byte[2048];
	int length;
 
	while ((length = is.read(b)) != -1) {
		os.write(b, 0, length);
	}
 
	is.close();
	os.close();
}
Category >> I/O  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>
  • anthony.pampag

    anthonyp[ampag