How to get the exact size of cache directory : android

android, caching

Solution

Calling length on a directory doesn't always return the correct size. You could try to iterate over the file list and add up all file sizes to get the total directory size.

Like this:

long size = 0;
File[] files = cacheDirectory.listFiles();
for (File f:files) {
    size = size+f.length();
}

Problem

NEED: I simply trying to get occupied cache size of each application which is installed in my phone. MY APPROACH: ``` PackageManager packageManager = getPackageManager(); List<ApplicationInfo> packages = packageManager.getInstalledApplications(PackageManager.GET_META_DATA); for (ApplicationInfo packageInfo : packages) { try { Context mContext = createPackageContext(packageInfo.packageName, CONTEXT_IGNORE_SECURITY); File cacheDirectory = mContext.getCacheDir(); if(cacheDirectory==null) { cacheArrayList.add("0"); } else { cacheArrayList.add(String.valueOf(cacheDirectory.length()/1024)); } } catch (NameNotFoundException e) { e.printStackTrace(); } } ``` RESULT: If directory is null it returning 0 (as condition). But if directory existing its returning 4 Kb always. I checked out cache of my apps by following the process: Settings:->Apps:->ApplicationName But I found its 0B there. Why its happening can someone explain? and How do I get exact size of cache?

Original source

Related problems