如何在java中从URL计算文件大小

我试图从Web服务获取一堆pdf链接,我想给用户提供每个链接的文件大小。

有没有办法完成这项任务?

谢谢

使用HEAD请求,您可以执行以下操作:

 private static int getFileSize(URL url) { URLConnection conn = null; try { conn = url.openConnection(); if(conn instanceof HttpURLConnection) { ((HttpURLConnection)conn).setRequestMethod("HEAD"); } conn.getInputStream(); return conn.getContentLength(); } catch (IOException e) { throw new RuntimeException(e); } finally { if(conn instanceof HttpURLConnection) { ((HttpURLConnection)conn).disconnect(); } } } 

尝试使用HTTP HEAD方法。 它仅返回HTTP标头。 标题Content-Length应包含您需要的信息。

接受的答案很容易出现NullPointerException ,对于文件> 2GiB不起作用,并且包含对getInputStream()的不必要调用。 这是固定代码:

 public long getFileSize(URL url) { HttpURLConnection conn = null; try { conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("HEAD"); return conn.getContentLengthLong(); } catch (IOException e) { throw new RuntimeException(e); } finally { if (conn != null) { conn.disconnect(); } } } 

更新:已接受的答案得到修复。

您是否已尝试在URL连接上使用getContentLength ? 如果服务器响应有效标头,您应该获得文档的大小。

但请注意,Web服务器也可能会以块的forms返回文件。 在这种情况下,IIRC内容长度方法将返回一个块(<= 1.4)或-1(> 1.4)的大小。

HTTP响应具有Content-Length标头,因此您可以在URLConnection对象中查询此值。

打开URL连接后,您可以尝试以下方法:

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

你可以尝试这个..

 private long getContentLength(HttpURLConnection conn) { String transferEncoding = conn.getHeaderField("Transfer-Encoding"); if (transferEncoding == null || transferEncoding.equalsIgnoreCase("chunked")) { return conn.getHeaderFieldInt("Content-Length", -1); } else { return -1; }