How can I get the size of a folder on SD card in Android?

Viewed 34839

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?

11 Answers

Hope this helps

import this

import android.text.format.Formatter;

For file size

public static String fileSize(File file, Context context) {
        return Formatter.formatFileSize(context, file.length());
    }

For folder size

 public static String forlderSize(File file, Context context) {
        long length = 0;
        File[] folderFiles = file.listFiles();
        for (File f : folderFiles) {
            length += f.length();
        }

        return Formatter.formatFileSize(context, length);
    }

Here's a snippet from Linh Toòng's answer with a couple more checks (mainly to stop Android Studio's warnings!)

private long getFolderSize(File file) {

        if (file == null || !file.exists())
            return 0;

        long size = 0;

        if (file.isDirectory()) {

            File[] files = file.listFiles();

            if (files == null || files.length == 0)
                return size;

            for (File f : files)
                size += getFolderSize(f);

        } else
            size += file.length();

        return size;

    }
Related