【问题标题】:How to get a file size in Bytes or in MB's through a URL如何通过 URL 以字节或 MB 为单位获取文件大小
【发布时间】:2014-03-16 05:18:06
【问题描述】:

我是 Java 新手。我试图从 URL 获取文件大小但失败了,谁能帮我获取 URL 大小(以字节为单位)?

【问题讨论】:

  • 你试过什么?你想用它做什么?您使用哪些库?请提供更多信息。

标签: java file-io content-length http-content-length


【解决方案1】:

【讨论】:

  • 请记住,并非所有 URL 都会返回长度,ts 会归结为服务器返回的长度
【解决方案2】:
    File file =new File("xxxxx"); // file path

    if(file.exists()){
        double bytes = file.length();
        double kilobytes = (bytes / 1024);
        System.out.println("bytes : " + bytes);
        double megabytes = (kilobytes / 1024);
        System.out.println("kilobytes : " + kilobytes);
        double gigabytes = (megabytes / 1024);
        System.out.println("megabytes : " + megabytes);
        double terabytes = (gigabytes / 1024);
        System.out.println("gigabytes : " + gigabytes);
        double petabytes = (terabytes / 1024);
    }else{
         System.out.println("File does not exists!");
    }

【讨论】:

  • 很抱歉,这与网址无关
  • 对不起,我只是误解了这个问题。
【解决方案3】:
public int getFileSizeInBytes(String path){
try {
        URL url=new URL(path);
        URLConnection urlConnection=url.openConnection();
        urlConnection.connect();
        int file_size=urlConnection.getContentLength();
        return  file_size;

    } catch (MalformedURLException e) {

    }catch (IOException e){

    }
    return -1;
}

【讨论】:

    猜你喜欢
    • 2012-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-03
    • 2013-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多