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

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

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

使用Apache Common IO中的FileUtils来简化问题:

 import org.apache.commons.io.FileUtils FileUtils.copyURLToFile(url, f); 

该方法下载的URL, url ,并保存到文件f

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

这也允许您将图像转换为其他格式,如果需要的话。

为了从http url创build一个文件,你需要从这个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(); 

下载的文件将在您的项目的根目录下find:{project} /downloaded.jpg

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

自Java 7以来

 File file = Paths.get(url.toURI()).toFile(); 
 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()); } }