Java – The fastest way to determine the size of a directory on an SD card on Android

The fastest way to determine the size of a directory on an SD card on Android… here is a solution to the problem.

The fastest way to determine the size of a directory on an SD card on Android

What is the fastest, hacking-free way to determine the size of a (flat, non-nested) directory on Android? Using the File object to get a list of files and enumerate them is prohibitively slow to calculate the size – is there certainly a better way?

(I know I can use threads in the background to calculate the size, but that’s not the ideal solution in this case).

Solution

You can also use this method, similar to another suggested method

public static long getDirSize(File dir) {
    try {
        Process du = Runtime.getRuntime().exec("/system/bin/du -sc " + dir.getCanonicalPath(), new String[]{}, Environment.getRootDirectory());
        BufferedReader br = new BufferedReader(new InputStreamReader(du.getInputStream()));
        String[] parts = br.readLine().split("\\s+");
        return Long.parseLong(parts[0]);
    } catch (IOException e) {
        Log.w(TAG, "Could not find size of directory " + dir.getAbsolutePath(), e);
    }
    return -1;
}

It returns the size in kilobytes and –1 if an error is encountered.

Related Problems and Solutions