Download Image From URL In Java

By | July 29, 2018

Simple way to download image from url in java is like this:

String source = "https://www.google.co.id/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png";
    URL url = new URL(source);
    URLConnection urlConnection = url.openConnection();
    InputStream in = urlConnection.getInputStream();

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    byte[] buf = new byte[1024];
    int n = 0;
    while (-1!=(n=in.read(buf)))
    {
      out.write(buf, 0, n);
    }
    out.close();
    in.close();
    byte[] response = out.toByteArray();

    String home = System.getProperty("user.home");
    File f = new File(home + File.separator + "Desktop" + File.separator + "image.jpg");

    try (FileOutputStream fos = new FileOutputStream(f)) {
      fos.write(response);
    }

Download Image From URL In Java

Download Image From URL In Java

Leave a Reply

Your email address will not be published. Required fields are marked *