我需要从URL对象创建一个File对象我的要求是我需要创建一个Web图像的文件对象(比如googles logo)
URL url = new URL("http://google.com/pathtoaimage.jpg");
File f = create image from url object
Run Code Online (Sandbox Code Playgroud)
gig*_*dot 85
import org.apache.commons.io.FileUtils
FileUtils.copyURLToFile(url, f);
Run Code Online (Sandbox Code Playgroud)
该方法下载内容url
并将其保存到f
.
Asu*_*Asu 39
自Java 7起
File file = Paths.get(url.toURI()).toFile();
Run Code Online (Sandbox Code Playgroud)
Cos*_*atu 23
您可以使用ImageIO
以从URL加载图像,然后将其写入文件.像这样的东西:
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);
Run Code Online (Sandbox Code Playgroud)
如果需要,这还允许您将图像转换为其他格式.
Liv*_* T. 13
要从HTTP URL创建文件,您需要从该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();
Run Code Online (Sandbox Code Playgroud)
下载的文件将在项目的根目录中找到:{project} /downloaded.jpg
小智 12
URL url = new URL("http://google.com/pathtoaimage.jpg");
File f = new File(url.getFile());
Run Code Online (Sandbox Code Playgroud)