Android,快速有效地查找目录大小的方法? [英] Android, Fast and efficient way of finding a directory size?

查看:364
本文介绍了Android,快速有效地查找目录大小的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我想找到许多目录的大小,并且我需要它快速运行.我已经看到了这些方法,其中两种方法不够快,而第三种方法仅适用于Java,而不适用于Android.

In my app, I want to find the size of many directories and I need it run fast. I have seen these methods, two of which are not fast enough and the third is just for Java, not Android.

public static long folderSize(File directory) {
long length = 0;
for (File file : directory.listFiles()) {
    if (file.isFile())
        length += file.length();
    else
        length += folderSize(file);
}
return length;
}

第二:

使用Apache FileUtils

使用Java 7 nio api,该api在android中不起作用

还有什么其他快速有效的方法可以使用?

What other fast and efficient way is there to be used?

推荐答案

使用StatFs可以快速估算目录大小.

我们尝试使用du -hsc,并且尝试使用Apache FileUtils,但是对于大型和复杂的目录,两者都太慢了.

Use StatFs to get a lightning-fast estimate of a directory size.

We tried using du -hsc and we tried using Apache FileUtils but both were far too slow for large and complex directories.

然后,我们偶然发现了StatFs,并被表演震撼了.它不那么准确,但是非常非常快.在我们的例子中,比duFileUtils快约1000倍.

Then we stumbled upon StatFs and were blown away by the performance. It's not as accurate but it's very very quick. In our case, about 1000x faster than either du or FileUtils.

似乎正在使用文件系统中内置的统计信息来获取估计的目录大小.这是粗略的实现:

It appears to be using the stats built into the file system to get the estimated directory size. Here's the rough implementation:

// Wicked-quick method of getting an estimated directory size without having to recursively
// go through each directory and sub directory and calculate the size.
//
public static long getDirectorySizeInBytes( File directory ) {
    if ( Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2 ) return 0; // API < 18 does not support `getTotalBytes` or `getAvailableBytes`.

    StatFs statFs = new StatFs( directory.getAbsolutePath() );

    return statFs.getTotalBytes() - statFs.getAvailableBytes();
}

这篇关于Android,快速有效地查找目录大小的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆