获取目录大小的方法返回不同的结果

Oma*_*mar 1 java directory size android file

我想在Android上获取文件夹的大小.问题是:

  1. 每次函数返回不同的东西.
  2. 它不扫描所有文件.

有人可以告诉我为什么吗?

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
}
Run Code Online (Sandbox Code Playgroud)

我从另一个线程得到了这个函数.我该如何改进这段代码?

dev*_*ity 6

最后摆脱分裂.每个子文件夹都被舍入到最接近的MB,并以字节为单位添加到当前文件夹的大小.返回字节并在调用者中处理转换.