How to create file object from URL object (image)

Java

Java Problem Overview


I need to create a File object from URL object My requirement is I need to create a file object of a web image (say googles logo)

URL url = new URL("http://google.com/pathtoaimage.jpg");
File f = create image from url object

Java Solutions


Solution 1 - Java

Use Apache Common IO's FileUtils:

import org.apache.commons.io.FileUtils

FileUtils.copyURLToFile(url, f);

The method downloads the content of url and saves it to f.

Solution 2 - Java

Since Java 7

File file = Paths.get(url.toURI()).toFile();

Solution 3 - Java

You can make use of ImageIO in order to load the image from an URL and then write it to a file. Something like this:

URL url = new URL("http://google.com/pathtoaimage.jpg");
BufferedImage img = ImageIO.read(url);
File file = new File("downloaded.jpg");
ImageIO.write(img, "jpg", file);

This also allows you to convert the image to some other format if needed.

Solution 4 - Java

You can convert the URL to a String and use it to create a new File. e.g.

URL url = new URL("http://google.com/pathtoaimage.jpg");
File f = new File(url.getFile());

Solution 5 - Java

In order to create a File from a HTTP URL you need to download the contents from that URL:

URL url = new URL("http://www.google.ro/logos/2011/twain11-hp-bg.jpg");
URLConnection connection = url.openConnection();
InputStream in = connection.getInputStream();
FileOutputStream fos = new FileOutputStream(new File("downloaded.jpg"));
byte[] buf = new byte[512];
while (true) {
    int len = in.read(buf);
    if (len == -1) {
        break;
    }
    fos.write(buf, 0, len);
}
in.close();
fos.flush();
fos.close();

The downloaded file will be found at the root of your project: {project}/downloaded.jpg

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionnidhinView Question on Stackoverflow
Solution 1 - JavagigadotView Answer on Stackoverflow
Solution 2 - JavaAsuView Answer on Stackoverflow
Solution 3 - JavaCosti CiudatuView Answer on Stackoverflow
Solution 4 - JavaArthur bauerView Answer on Stackoverflow
Solution 5 - JavaLiviu T.View Answer on Stackoverflow