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

查看:394
本文介绍了如何在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天全站免登陆