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

jav*_*Man 18 java java-ee

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

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

谢谢

小智 36

使用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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 它返回-1.当我在调试模式下运行并查看conn对象时,我看到许多字段为null或false或-1 (2认同)

Ale*_*exR 8

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


Mic*_*ung 6

接受的答案很容易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();
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

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