http Java URLConnection:如何确定web文件的大小?
我正在为学校做一个项目,我正在实现一个工具,可以用来从网上下载文件(带有限制选项)。问题是,我将有一个GUI,我将使用一个JProgressBar
小部件,我想显示下载的当前进度。为此,我需要知道文件的大小。如何在下载文件之前获得文件的大小
你可以在下面搜索框中键入要查询的问题!
我正在为学校做一个项目,我正在实现一个工具,可以用来从网上下载文件(带有限制选项)。问题是,我将有一个GUI,我将使用一个JProgressBar
小部件,我想显示下载的当前进度。为此,我需要知道文件的大小。如何在下载文件之前获得文件的大小
# 1 楼答案
如前所述,URLConnection的^{} 是最好的选择,但它并不总是给出一个确定的长度。这是因为HTTP协议(以及其他可以用
URLConnection
表示的协议)并不总是传递长度在HTTP的情况下,动态内容的长度通常在通常发送
content-length
头时不预先知道。相反,另一个头transfer-encoding
指定使用“分块”编码。使用分块编码时,整个响应的长度是未指定的,并且响应以片段的形式发送回来,其中每个片段的大小都是指定的。实际上,服务器缓冲来自servlet的输出。每当缓冲区填满时,就会发送另一个块。使用这种机制,HTTP实际上可以开始流式传输无限长的响应如果文件大于2GB,则其大小不能表示为} 将返回-1
int
,因此在这种情况下,较旧的方法^{# 2 楼答案
您需要使用内容长度(URLConnection.getContentLength())。不幸的是,这并不总是准确的,或者可能并不总是提供的,因此依赖它并不总是安全的
# 3 楼答案
# 4 楼答案
正如@erickson所说,有时会出现标题“Transfer Encoding:chunked”,而不是“Content Length:”,当然,长度的值为空
关于available()方法-没有人能向您保证它将返回正确的值,因此我建议您不要使用它
# 5 楼答案
使用HEAD请求,我让我的Web服务器使用正确的内容长度字段进行回复,否则该字段为空。我不知道这在一般情况下是否有效,但在我的情况下确实有效:
# 6 楼答案
任何HTTP响应都假定包含一个内容长度头,因此您可以在URLConnection对象中查询该值
服务器可能并不总是能够返回准确的内容长度,因此该值可能不准确,但至少在大多数情况下,您会得到一些可用值
更新:或者,现在我更全面地了解了URLConnection javadoc,您可以使用getContentLength()方法