如何从java中的URL计算文件大小 [英] How to calculate a file size from URL in java

查看:66
本文介绍了如何从java中的URL计算文件大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm attempting to get a bunch of pdf links from a web service and I want to give the user the file size of each link.

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

Is there a way to accomplish this task?

谢谢

推荐答案

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

Using a HEAD request, you can do something like this:

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();
        }
    }
}

这篇关于如何从java中的URL计算文件大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆