有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

http Java URLConnection:如何确定web文件的大小?

我正在为学校做一个项目,我正在实现一个工具,可以用来从网上下载文件(带有限制选项)。问题是,我将有一个GUI,我将使用一个JProgressBar小部件,我想显示下载的当前进度。为此,我需要知道文件的大小。如何在下载文件之前获得文件的大小


共 (6) 个答案

  1. # 1 楼答案

    如前所述,URLConnection的^{}是最好的选择,但它并不总是给出一个确定的长度。这是因为HTTP协议(以及其他可以用URLConnection表示的协议)并不总是传递长度

    在HTTP的情况下,动态内容的长度通常在通常发送content-length头时不预先知道。相反,另一个头transfer-encoding指定使用“分块”编码。使用分块编码时,整个响应的长度是未指定的,并且响应以片段的形式发送回来,其中每个片段的大小都是指定的。实际上,服务器缓冲来自servlet的输出。每当缓冲区填满时,就会发送另一个块。使用这种机制,HTTP实际上可以开始流式传输无限长的响应

    如果文件大于2GB,则其大小不能表示为int,因此在这种情况下,较旧的方法^{}将返回-1

  2. # 2 楼答案

    您需要使用内容长度(URLConnection.getContentLength())。不幸的是,这并不总是准确的,或者可能并不总是提供的,因此依赖它并不总是安全的

  3. # 3 楼答案

        //URLConnection connection
    
    private int FileSize(String url) {
    
     // this is the method and it get the url as a parameter.
    
           // this java class will allow us to get the size of the file.
    
            URLConnection con; 
    
             // its in a try and catch incase the url given is wrong or invalid
    
            try{ 
    
                // we open the stream
    
                con = new URL(url).openConnection()
    
                return con.getContentLength(); 
            }catch (Exception e){
    
                e.printStackTrace();
    
                // this is returned if the connection went invalid or failed.
    
                return 0; 
            }
        }
    
  4. # 4 楼答案

    正如@erickson所说,有时会出现标题“Transfer Encoding:chunked”,而不是“Content Length:”,当然,长度的值为空

    关于available()方法-没有人能向您保证它将返回正确的值,因此我建议您不要使用它

  5. # 5 楼答案

    使用HEAD请求,我让我的Web服务器使用正确的内容长度字段进行回复,否则该字段为空。我不知道这在一般情况下是否有效,但在我的情况下确实有效:

        private int tryGetFileSize(URL url) {
            HttpURLConnection conn = null;
            try {
                conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("HEAD");
                conn.getInputStream();
                return conn.getContentLength();
            } catch (IOException e) {
                return -1;
            } finally {
                conn.disconnect();
            }
        }
    
  6. # 6 楼答案

    任何HTTP响应都假定包含一个内容长度头,因此您可以在URLConnection对象中查询该值

    //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...
           ...
        }
    

    服务器可能并不总是能够返回准确的内容长度,因此该值可能不准确,但至少在大多数情况下,您会得到一些可用值

    更新:或者,现在我更全面地了解了URLConnection javadoc,您可以使用getContentLength()方法