Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to calculate folder size in Gingerbread(2.3)

Tags:

android

I am calculating a folder size in my application using "file.length()". It is working fine in other versions of Android O.S. and I am getting my folder size in Bytes. But the problem is that when I am running the same code for a device having Gingerbread in it, its always showing me size as 0 Bytes. I am not able to understand the problem. Here is my code :-

File file1=new File(android.os.Environment.getExternalStorageDirectory(),"/.Gallery");

double total_length = file1.length();

Please help me to solve this, any help would be appreciable.

Thanks in advance.

like image 404
Salman Khan Avatar asked Nov 28 '13 12:11

Salman Khan


1 Answers

From android documentantion:

File.lenght(): Returns the length of this file in bytes. Returns 0 if the file does not exist. The result for a directory is not defined.

You may used this to compute directory lenght:

public static long getFolderSize(File folderPath) {

    long totalSize = 0;

    if (folderPath == null) {
      return 0;
    }

    if (!folderPath.isDirectory()) {
      return 0;
    }

    File[] files = folderPath.listFiles();
    if(files != null){
        for (File file : files) {
          if (file.isFile()) {
            totalSize += file.length();
          } else if (file.isDirectory()) {
            totalSize += file.length();
            totalSize += getFolderSize(file);
          }
        }
    }
    return totalSize;
}
like image 84
ramaral Avatar answered Sep 29 '22 16:09

ramaral