Giorgio Antonioli
Giorgio Antonioli

Reputation: 16214

Obtain size of a file from his path

I'm trying to get the size of a file by his path. I don't know where I'm doing wrong because I can get all the other informations, but when I try to get size of the file, it returns 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());

I obtain all other information rights, so it isn't a path problem.

Upvotes: 0

Views: 167

Answers (3)

Hareshkumar Chhelana
Hareshkumar Chhelana

Reputation: 24848

Simply use length() and convert kb,mb,gb etc :

File file =new File(filePath);

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!");
}

Upvotes: 0

BarrySW19
BarrySW19

Reputation: 3809

You will get the file name even if the file doesn't exist. What does file.exists() return? I'm guessing false. Carefully check your path.

Upvotes: 1

Don Chakkappan
Don Chakkappan

Reputation: 7560

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

Upvotes: 0

Related Questions