How to download Image from Url Using Java

 Posted On  | Yashwant Chavan 

In this tutorial we are going to discuss, How to download Image from Url and save it to local disk. App.java helps you to download the respected Url image to your local file system path.

App.java

Class URL represents a Uniform Resource Locator, a pointer to a "resource" on the World Wide Web. A resource can be something as simple as a image location, file or a directory, or it can be a reference to a more complicated object. Once you are ale to locate the Image Url , just read the image bytes and write it using FileOutputStream.

Before execute the App.java, Please make sure that your internet connection is available. So that It can connect the respected image path and download the images bytes.

package com.technicalkeeda.app;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;

public class App {

    public static void main(String[] args) {
        String imageUrl = "http://www.technicalkeeda.com/img/images/article/spring-file-upload-eclipse-setup.png";

        InputStream inputStream = null;
        OutputStream outputStream = null;

        try {
            URL url = new URL(imageUrl);
            inputStream = url.openStream();
            outputStream = new FileOutputStream("c:\\spring-file-upload-eclipse-setup.jpg");

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

            while ((length = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, length);
            }

        } catch (MalformedURLException e) {
            System.out.println("MalformedURLException :- " + e.getMessage());

        } catch (FileNotFoundException e) {
            System.out.println("FileNotFoundException :- " + e.getMessage());

        } catch (IOException e) {
            System.out.println("IOException :- " + e.getMessage());

        } finally {
            try {

                inputStream.close();
                outputStream.close();

            } catch (IOException e) {
                System.out.println("Finally IOException :- " + e.getMessage());
            }
        }
    }

}


© technicalkeeda.com 2017

 |  Find us on Google+ |  Rss Feed

Loaded in 0.0299 seconds.