Java URLConnection:如何找出Web文件的大小? [英] Java URLConnection : how can I find out the size of a web file?
问题描述
我正在为学校开展项目,我正在实施一个可用于从网上下载文件的工具(带有限制选项)。问题是,我将有一个GUI,我将使用 JProgressBar
小部件,我想展示下载的当前进度。为此,我需要知道文件的大小。如何在下载文件之前获取文件的大小。
I'm working on a project for school, and I'm implementing a tool which can be used to download files from the web ( with a throttling option ). The thing is, I'm gonna have a GUI for it, and I will be using a JProgressBar
widget, which I would like to show the current progress of the download. For that I would need to know the size of the file. How do you get the size of the file prior to downloading the file.
推荐答案
任何HTTP响应假设包含Content-Length标头,因此您可以查询此值的URLConnection对象。
Any HTTP response is supposed to contain a Content-Length header, so you could query the URLConnection object for this value.
//once the connection has been opened
List values = urlConnection.getHeaderFields().get("content-Length")
if (values != null && !values.isEmpty()) {
// getHeaderFields() returns a Map with key=(String) header
// name, value = List of String values for that header field.
// just use the first value here.
String sLength = (String) values.get(0);
if (sLength != null) {
//parse the length into an integer...
...
}
服务器可能无法始终返回准确的内容长度,因此值可能不准确,但至少你在大多数情况下会得到一些可用值。
It might not always be possible for a server to return an accurate Content-Length, so the value could be inaccurate, but at least you would get some usable value most of the time.
更新:或者,现在我看看URLConnection更完整的javadoc,你可以使用 getContentLength()方法。
update: Or, now that I look at the URLConnection javadoc more completely, you could just use the getContentLength() method.
这篇关于Java URLConnection:如何找出Web文件的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!