如何从 URL 对象(图像)创建文件对象

我需要从 URL 对象创建一个 File 对象 我的要求是 我需要创建一个网络图像的文件对象(例如谷歌标志)

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

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

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 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.

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