如何从URL对象创建文件对象

nid*_*hin 82 java

我需要从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

使用Apache Common IOFileUtils:

import org.apache.commons.io.FileUtils

FileUtils.copyURLToFile(url, f);
Run Code Online (Sandbox Code Playgroud)

该方法下载内容url并将其保存到f.

  • 这对我有用:`URL url = new URL("http://www.mydomain.com/pathToFile/fileName.pdf"); String tDir = System.getProperty("java.io.tmpdir"); String path = tDir +"tmp"+".pdf"; file = new File(path); file.deleteOnExit(); FileUtils.copyURLToFile(url,file);` (14认同)

Asu*_*Asu 39

自Java 7起

File file = Paths.get(url.toURI()).toFile();
Run Code Online (Sandbox Code Playgroud)

  • 这是用于检索文件位置,例如`file://`协议,不确定OP是否需要该位置或下载图像本身,但无论如何这是我个人寻找的.谢谢 (5认同)

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)

  • 将此方法用于在完整路径中有空格的本地文件系统文件时,%20将不会自动转换为空格并可能导致异常 (7认同)