-2

我是 Java 新手。我试图从 URL 获取文件大小,但我失败了,任何人都可以帮助我如何获取以字节为单位的 URL 大小吗?

4

3 回答 3

2

使用从其中获得的getContentLength方法URLConnectionURL#openConnection

于 2014-03-16T05:41:28.300 回答
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!");
    }
于 2014-03-16T05:33:18.773 回答
0
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;
}
于 2016-06-17T16:19:56.897 回答