Log in
updated 11:29 AM UTC, May 4, 2016

How to download Images in Java and how Threads help in downloading them faster

  • Written by Madhu V Rao
  • Published in Core Java

This program explains how to download an Image using Java. This uses Java thread's for parallelly downloading the Images.By commenting out the lines (1, 2 ,3 and 4 ) which is specified as the comments, the program downloads the images sequentially.

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import javax.imageio.ImageIO;
/**
 *
 * @author M.Vasudevarao
 */
public class ImageDownloader
{
    public static final String fileSep = System.getProperty("file.separator");
    private String httpURLofImage;

    public ImageDownloader(String url)
    {
        httpURLofImage = url;
    }

    public void download(String fileName)
    {
        BufferedImage img;
        URL url = null;
        try
        {

            URI uri = new URI(
                    "http",
                    httpURLofImage,
                    "/" + fileName,
                    null);
            url = uri.toURL();
            img = ImageIO.read(url);
            File os = new File(fileName);
            ImageIO.write(img, "jpg", os);
            System.out.println(Thread.currentThread().getName()+ " downloaded");
        }
        catch (URISyntaxException ex)
        {
            ex.printStackTrace();
        }
        catch (IOException ex)
        {
            System.out.println("Some problem with the file "+ fileName + " -IOEXCEPTION");
        }
    }

    public static void main(final String args[])
    {
        System.out.println("args.length " + args.length);
        final String url = args[0];
        for (int i = 1; i < args.length; i++)
        {
            final String fileName = args[i];
            (new Thread(fileName)  //line 1 - Anonymous inner Thread Class
            {                                      //line 2
                public void run()         //line 3
                {
                    new ImageDownloader(url).download(fileName);
                }                                
            }).start();                       //line 4
        }
    }
}

Compile:

javac ImageDownloader.java

How to run:

before running create a folder images and execute the following command:

java ImageDownloader ictforu.com images/comm.jpg images/digital_video_broadcasting_logo.svg.png

 run it twice once with Java Threads and other without it and see the performance improvement by yourself.


Powered by Bullraider.com
Follow Us on Twitter
Find Us on Facebook
Follow Us on Google
Follow Us on Pinterest