Search code examples
androidandroid-storage

Check avaliable space by getDataDirectory() and getRootDirectory() is not same


I try to check available space on my android phone by using getDataDirectory().getPath() and getRootDirettory().getAbsolutePath() and I got these results,

Using getRootDirectory().getAbsolutePath()

StatFs statFs = new StatFs(Environment.getRootDirectory().getAbsolutePath());
    Log.w("Path", String.valueOf(Environment.getRootDirectory()) );
    Log.w("Path", Environment.getRootDirectory().getAbsolutePath());
    long free_memory = statFs.getAvailableBlocksLong() * statFs.getBlockSizeLong();
    Log.d("Available byte by Environment.getRootDirectory().getAbsolutePath(): ", String.valueOf(free_memory/1048576));

Logcat:

W/Path: /system

W/Path: /system

W/Available byte by Environment.getRootDirectory().getAbsolutePath():: 91


Using getRootDirectory().getPath()

statFs = new StatFs(Environment.getDataDirectory().getPath());
    Log.w("Path", String.valueOf(Environment.getDataDirectory()) );
    Log.w("Path", Environment.getDataDirectory().getPath());
    long free_memory02 = statFs.getAvailableBlocksLong() * statFs.getBlockSizeLong();
    Log.d("Available byte by Environment.getDataDirectory().getPath(): ", String.valueOf(free_memory02/1048576));

Logcat:

W/Path: /data

W/Path: /data

W/Available byte by Environment.getDataDirectory().getPath():: 21426 MB or 20.924 GB

but when I check available space from setting in my phone in only show: 20.34 GB

What is the best accurate way to check available space in my phone and why getRootDirectory().getAbsolutePath() and getDataDirectory.getPath() not give the same space?


Solution

  • What is the best accurate way to check available space

    It is better to use Environment.getExternalStorageDirectory() for checking available memory.

    There are different partitions in Internal storage.

    /data partition : Has user data only. //getDataDirectory()

    /system partition : Holds the core Android OS. //getRootDirectory()

    why getRootDirectory().getAbsolutePath() and getDataDirectory().getPath() not give the same space?

    Because they are different directories.

    You can use

      final StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
      long totalinternal = (long) stat.getBlockSize() * (long) stat.getBlockCount();
      long available = (long) stat.getBlockSize() * (long) stat.getAvailableBlocks();