views:

35

answers:

2

Is it possible to easily get the size of a folder on the SD card? I use a folder for caching of images, and would like to present the total size of all cached images. Is there a way to this other than iterating over each file? They all reside inside the same folder?

A: 

Just go through all files and sum the length of them:

/**
 * Return the size of a directory in bytes
 */
private static long dirSize(File dir) {
    long result = 0;
    File[] fileList = dir.listFiles();

    for(int i = 0; i < dirlist.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
}

NOTE: Function written by hand so it could not compile!

EDITED: recursive call fixed.

Moss
You might want to replace findFile by dirSize :)
Maurits Rijk
A: 

Iterating through all files is less than 5 lines of code and the only reasonable way to do this. If you want to get ugly you could also run a system command (Runtime.getRuntime().exec("du");) and catch the output ;)

Maurits Rijk
Fair enough. Just figured it was such a common use case that there should be some native solution. Laziness is good ... Five lines later, and I'm happy :)
Gunnar Lium
In Clojure: (defn dir-size [dir] (reduce + (map #(.length %) (.listFiles (new File dir)))))
Maurits Rijk