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, no
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.
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();
}