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

前端 未结 1 1574
夕颜
夕颜 2021-01-06 16:55

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

相关标签:
1条回答
  • 2021-01-06 17:39

    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();
    }
    
    0 讨论(0)
提交回复
热议问题