如何在Android中获取SD卡上文件夹的大小?

Gun*_*ium 28 directory size android sd-card

是否可以轻松获取SD卡上文件夹的大小?我使用一个文件夹来缓存图像,并希望显示所有缓存图像的总大小.除了遍历每个文件之外,还有其他方法吗?它们都驻留在同一个文件夹中?

Mos*_*oss 40

只需浏览所有文件并总结它们的长度:

/**
 * Return the size of a directory in bytes
 */
private static long dirSize(File dir) {

    if (dir.exists()) {
        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; // return the file size
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

注意:手写的功能无法编译!

编辑:递归调用修复.

已编辑:dirList.length已更改为fileList.length.


and*_*per 16

这里有一些代码可以避免递归,还可以计算物理大小而不是逻辑大小:

public static long getFileSize(final File file) {
    if (file == null || !file.exists())
        return 0;
    if (!file.isDirectory())
        return file.length();
    final List<File> dirs = new LinkedList<>();
    dirs.add(file);
    long result = 0;
    while (!dirs.isEmpty()) {
        final File dir = dirs.remove(0);
        if (!dir.exists())
            continue;
        final File[] listFiles = dir.listFiles();
        if (listFiles == null || listFiles.length == 0)
            continue;
        for (final File child : listFiles) {
            result += child.length();
            if (child.isDirectory())
                dirs.add(child);
        }
    }
    return result;
}
Run Code Online (Sandbox Code Playgroud)


小智 5

/**
 * Try this one for better performance
 * Mehran
 * Return the size of a directory in bytes
 **/

private static long dirSize(File dir) {
    long result = 0;

    Stack<File> dirlist= new Stack<File>();
    dirlist.clear();

    dirlist.push(dir);

    while(!dirlist.isEmpty())
    {
        File dirCurrent = dirlist.pop();

        File[] fileList = dirCurrent.listFiles();
        for(File f: fileList){
            if(f.isDirectory())
                dirlist.push(f);
            else
                result += f.length();
        }
    }

    return result;
}
Run Code Online (Sandbox Code Playgroud)

  • 由于我们讨论的是文件操作,因此递归不太可能解决大部分性能问题.此外,java.util.Stack实现非常慢.我尝试用它来优化递归算法,然后让JVM完成它的工作实际上要慢一些. (2认同)

小智 5

你应该使用这个代码:

public static long getFolderSize(File f) {
    long size = 0;
    if (f.isDirectory()) {
        for (File file : f.listFiles()) {    
            size += getFolderSize(file);
        }
    } else {
        size=f.length();
    }
    return size;
}
Run Code Online (Sandbox Code Playgroud)