Unable to calculate folder size in Gingerbread (2.3)

I calculate the size of the folder in my application using "file.length ()". It works fine in other versions of Android OS and I get my folder size in bytes. But the problem is that when I run the same code for a device that has Gingerbread, it always shows me the size as 0 bytes. I can not understand the problem. Here is my code: -

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

Please help me solve this problem, any help will be noticeable.

Thanks in advance.

+6
source share
1 answer

From the documentary android:

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

You can use this to calculate directory length:

 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; } 
+1
source

Source: https://habr.com/ru/post/958985/


All Articles