logo image

How to download an image from Internet using Java?



Using following code you can down load an image from Internet (from a URL resource). Note that you need to change the String values of imageUrl, destinationFilePath as per your requirements. imageUrl - URL of the image you want to download destinationFilePath - The local File System path where you want to store the Image

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;

public class DownloadImage {
	public static void main(String[] args) {

		String imageUrl = "http://via.placeholder.com/350x150";
		String destinationFilePath = "/path/to/file/test.jpg"; // For windows something like c:\\path\to\file\test.jpg

		InputStream inputStream = null;
		try {
			inputStream = new URL(imageUrl).openStream();
			Files.copy(inputStream, Paths.get(destinationFilePath));
		} catch (IOException e) {
			System.out.println("Exception Occurred " + e);
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					// Ignore
				}
			}
		}

	}
}