【发布时间】:2014-03-16 05:18:06
【问题描述】:
我是 Java 新手。我试图从 URL 获取文件大小但失败了,谁能帮我获取 URL 大小(以字节为单位)?
【问题讨论】:
-
你试过什么?你想用它做什么?您使用哪些库?请提供更多信息。
标签: java file-io content-length http-content-length
我是 Java 新手。我试图从 URL 获取文件大小但失败了,谁能帮我获取 URL 大小(以字节为单位)?
【问题讨论】:
标签: java file-io content-length http-content-length
【讨论】:
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!");
}
【讨论】:
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;
}
【讨论】: