How to get the exact size of cache directory : android

前端 未结 3 1577
别跟我提以往
别跟我提以往 2020-12-14 22:14

NEED: I simply trying to get occupied cache size of each application which is installed in my phone.

MY APPROACH:

PackageManager packageManager = get         


        
3条回答
  •  执笔经年
    2020-12-14 23:11

    This has been more accurate to me:

    private void initializeCache() {
        long size = 0;
        size += getDirSize(this.getCacheDir());
        size += getDirSize(this.getExternalCacheDir());
        ((TextView) findViewById(R.id.yourTextView)).setText(readableFileSize(size));
    }
    
    public long getDirSize(File dir){
        long size = 0;
        for (File file : dir.listFiles()) {
            if (file != null && file.isDirectory()) {
                size += getDirSize(file);
            } else if (file != null && file.isFile()) {
                size += file.length();
            }
        }
        return size;
    }
    
    public static String readableFileSize(long size) {
        if (size <= 0) return "0 Bytes";
        final String[] units = new String[]{"Bytes", "kB", "MB", "GB", "TB"};
        int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
        return new DecimalFormat("#,##0.#").format(size / Math.pow(1024, digitGroups)) + " " + units[digitGroups];
    }
    

    Original post of the string to bytes formatting code

提交回复
热议问题