How to create file object from URL object (image) [duplicate]

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

Solution 1:

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:

Since Java 7

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

Solution 3:

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.