Java URLConnection : how can I find out the size of a web file?(Java URLConnection :我怎样才能找出网络文件的大小?)
问题描述
我正在为学校做一个项目,我正在实现一个可用于从网络下载文件的工具(带有限制选项).问题是,我将有一个 GUI,我将使用一个 JProgressBar
小部件,我想显示下载的当前进度.为此,我需要知道文件的大小.在下载文件之前如何获取文件的大小.
应该任何 HTTP 响应都包含 Content-Length 标头,因此您可以查询 URLConnection 对象以获取此值.p>
//一旦打开连接列表值 = urlConnection.getHeaderFields().get("content-Length")if (values != null && !values.isEmpty()) {//getHeaderFields() 返回带有 key=(String) 标头的 Map//name, value = 该标头字段的字符串值列表.//这里只使用第一个值.String sLength = (String) values.get(0);如果(sLength!= null){//将长度解析为整数......}
服务器可能无法始终返回准确的 Content-Length,因此该值可能不准确,但至少在大多数情况下您会得到一些可用值.p>
更新: 或者,现在我更完整地查看了 URLConnection javadoc,您可以只使用 getContentLength() 方法.
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.
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.
update: Or, now that I look at the URLConnection javadoc more completely, you could just use the getContentLength() method.
这篇关于Java URLConnection :我怎样才能找出网络文件的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java URLConnection :我怎样才能找出网络文件的大小?
基础教程推荐
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 降序排序:Java Map 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01