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

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

This question is related to java

The answer is


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.


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());

Since Java 7

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

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