Java程序,用于从网站下载图像并显示文件大小 [英] Java program to download images from a website and display the file sizes
问题描述
我正在创建一个Java程序,该程序将从URL中读取html文档,并在代码中显示图像的大小.我不确定如何实现这一目标.
I'm creating a java program that will read a html document from a URL and display the sizes of the images in the code. I'm not sure how to go about achieving this though.
我不需要实际下载和保存图像,我只需要图像的大小和在网页上显示的顺序即可.
I wouldn't need to actually download and save the images, i just need the sizes and the order in which they appear on the webpage.
例如:一个网页上有3张图片
for example: a webpage has 3 images
<img src="dog.jpg" /> //which is 54kb
<img src="cat.jpg" /> //which is 75kb
<img src="horse.jpg"/> //which is 80kb
我需要显示我的Java程序的输出
i would need the output of my java program to display
54kb
75kb
80kb
有什么想法我应该从哪里开始?
Any ideas where i should start?
p.s我有点像Java新手
p.s I'm a bit of a java newbie
推荐答案
如果您是Java的新手,您可能希望利用现有的库使事情变得简单一些. Jsoup 允许您获取HTML页面并使用CSS样式选择器提取元素.
If you're new to Java you may want to leverage an existing library to make things a bit easier. Jsoup allows you to fetch an HTML page and extract elements using CSS-style selectors.
这只是一个快速且非常的示例,但我认为它将显示Jsoup可以轻松完成这样的任务.请注意,省略了错误处理和响应代码处理,我只想传递一般想法:
This is just a quick and very dirty example but I think it will show how easy Jsoup can make such a task. Please note that error handling and response-code handling was omitted, I merely wanted to pass on the general idea:
Document doc = Jsoup.connect("http://stackoverflow.com/questions/14541740/java-program-to-download-images-from-a-website-and-display-the-file-sizes").get();
Elements imgElements = doc.select("img[src]");
Map<String, String> fileSizeMap = new HashMap<String, String>();
for(Element imgElement : imgElements){
String imgUrlString = imgElement.attr("abs:src");
URL imgURL = new URL(imgUrlString);
HttpURLConnection httpConnection = (HttpURLConnection) imgURL.openConnection();
String contentLengthString = httpConnection.getHeaderField("Content-Length");
if(contentLengthString == null)
contentLengthString = "Unknown";
fileSizeMap.put(imgUrlString, contentLengthString);
}
for(Map.Entry<String, String> mapEntry : fileSizeMap.entrySet()){
String imgFileName = mapEntry.getKey();
System.out.println(imgFileName + " ---> " + mapEntry.getValue() + " bytes");
}
您还可以考虑查看 Apache HttpClient .我发现它通常比原始URLConnection/HttpURLConnection方法更可取.
You might also consider looking at Apache HttpClient. I find it generally preferable over the raw URLConnection/HttpURLConnection approach.
这篇关于Java程序,用于从网站下载图像并显示文件大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!