2014-11-21 42 views
0

我試圖通過他的路徑獲取文件的大小。 我不知道我做錯了,因爲我可以得到所有的其它信息,但是當我試圖獲得該文件的大小,則返回0。從他的路徑獲取文件的大小

File file = new File(Environment.getExternalStorageDirectory(), MainActivity.filePath); 
long fileLength = file.length(); //here is where i get 0 
String fileSize = String.valueOf(fileLength); 
String fileName = file.getName(); 
String fileExtension = MainActivity.filePath.substring((MainActivity.filePath.lastIndexOf(".") + 1), MainActivity.filePath.length()); 

我獲得的所有其他信息的權利,所以它不是一個路徑問題。

+0

'file.length()'按預期工作。如果文件是目錄,文件爲空,如果無法讀取文件或者文件不存在,您將得到0。 – 2014-11-21 11:21:45

回答

0
File file=new File(path_to_file); 
FileInputStream fin=new FileInputStream(file); 
int size =fin.available(); 
1

即使文件不存在,您仍將獲得文件名。什麼是file.exists()返回?我猜猜錯了。仔細檢查你的路徑。

0

只需使用長度()和轉換KB,MB,GB等:

文件文件=新的文件(文件路徑);

if(file.exists()){ 

    double bytes = file.length(); 
    double kilobytes = (bytes/1024); 
    double megabytes = (kilobytes/1024); 
    double gigabytes = (megabytes/1024); 
    double terabytes = (gigabytes/1024); 
    double petabytes = (terabytes/1024); 
    double exabytes = (petabytes/1024); 
    double zettabytes = (exabytes/1024); 
    double yottabytes = (zettabytes/1024); 

    System.out.println("bytes : " + bytes); 
    System.out.println("kilobytes : " + kilobytes); 
    System.out.println("megabytes : " + megabytes); 
    System.out.println("gigabytes : " + gigabytes); 
    System.out.println("terabytes : " + terabytes); 
    System.out.println("petabytes : " + petabytes); 
    System.out.println("exabytes : " + exabytes); 
    System.out.println("zettabytes : " + zettabytes); 
    System.out.println("yottabytes : " + yottabytes); 
}else{ 
    System.out.println("File does not exists!"); 
}