java通过文件的URL获取文件大小

  • A+
所属分类:java 编程

此方法可在不下载文件的前提下,通过http head 请求,获取一个文件的大小;

java通过文件的URL获取文件大小

代码如下:

    /**
     * 获取网络文件的大小
     */
    public static long getFileLength(String fileUrl) throws IOException {
        if(fileUrl == null || "".equals(fileUrl)){
            return 0L ;
        }
        URL url = new URL(fileUrl);
        HttpURLConnection conn = null;
        try {
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("HEAD");
            conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows 7; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.73 Safari/537.36 YNoteCef/5.8.0.1 (Windows)");
            return (long) conn.getContentLength();
        } catch (IOException e) {
            return 0L;
        } finally {
            conn.disconnect();
        }
    }

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: