SSP
SSP

Reputation: 459

Android, Fast and efficient way of finding a directory size?

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.

First:

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;
}

Second:

Using Apache FileUtils

Third:

Using Java 7 nio api, which doesn't work in android

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

Upvotes: 5

Views: 3670

Answers (2)

Madushan
Madushan

Reputation: 7478

If you're using kotlin

val size = File(parentAbsolutePath,directoryName)
                .walkTopDown()
                .map { it.length() }
                .sum() // in bytes

Upvotes: 5

Joshua Pinter
Joshua Pinter

Reputation: 47611

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.

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

Upvotes: -1

Related Questions