A method to get Directory size returns different results
I'm trying to get the size of a folder on Android. The problems are:
- Each time the function returns something different.
- It doesn't scan all files.
Can someone tell me why?
private long dirSize(File dir) {
long result = 0;
File[] fileList = dir.listFiles();
for(int i = 0; i < fileList.length; i++) {
// Recursive call if it's a directory
if(fileList[i].isDirectory()) {
result += dirSize(fileList [i]);
} else {
// Sum the file size in bytes
result += fileList[i].length();
}
}
return result/1024/1024; // return the file size
}
开发者_如何学CI got this function from another thread. How can I improve this code?
Get rid of the division at the end. Each subfolder is being rounded to nearest MB, and added to the size of the current folder in bytes. Return bytes and handle conversion in the caller.
精彩评论