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

时间:2011-11-30 11:02:33

标签: java

我需要从URL对象创建一个File对象 我的要求是  我需要创建一个Web图像的文件对象(比如googles logo)

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

5 个答案:

答案 0 :(得分:83)

使用Apache Common IO's FileUtils

import org.apache.commons.io.FileUtils

FileUtils.copyURLToFile(url, f);

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

答案 1 :(得分:22)

您可以使用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);

如果需要,还可以将图像转换为其他格式。

答案 2 :(得分:12)

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

下载的文件将在项目的根目录中找到:{project} /downloaded.jpg

答案 3 :(得分:12)

URL url = new URL("http://google.com/pathtoaimage.jpg");
File f = new File(url.getFile());

答案 4 :(得分:-2)

import java.net.*; 
import java.io.*; 
class getsize { 
    public static void main(String args[]) throws Exception {
        URL url=new URL("http://www.supportyourpm.in/jatin.txt"); //Reading
        URLConnection yc = url.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null) 
            System.out.println(inputLine);
        in.close();

        //Getting size
        HttpURLConnection conn = null;
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("HEAD");
        conn.getInputStream();
        System.out.println("Length : "+conn.getContentLength());
    } 
}