-2

I am using the below method to find the available/free space of my external and internal directory. It returns me 4 GB for internal memory and 3.9 GB for external memory. But when i go to the story section of my phone, it is showing 3.7 GB available space. Why this mismatch.

 long freeBytesInternal = new File(ctx.getFilesDir().getAbsoluteFile().toString()).getFreeSpace();
   long freeBytesExternal = new File(ctx.getExternalFilesDir(null).toString()).getFreeSpace();
imi
  • 259
  • 1
  • 3
  • 14
  • https://stackoverflow.com/questions/8133417/android-get-free-size-of-internal-external-memory – ADM Jun 02 '18 at 07:12
  • 6
    Possible duplicate of [Android get free size of internal/external memory](https://stackoverflow.com/questions/8133417/android-get-free-size-of-internal-external-memory) – Learning Always Jun 02 '18 at 07:13
  • Even with the accepted answer i am getting it as 3.9 GB instead of 3.7 GB – imi Jun 02 '18 at 07:31

1 Answers1

0

To find available internal memory size :-

public static String getAvailableInternalMemorySize() {
    File path = Environment.getDataDirectory();
    StatFs stat = new StatFs(path.getPath());
    long blockSize = stat.getBlockSizeLong();
    long availableBlocks = stat.getAvailableBlocksLong();
    return formatSize(availableBlocks * blockSize);
}

 For External memory size:- 
   public static String getAvailableExternalMemorySize() {

        File path = Environment.getExternalStorageDirectory();
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSizeLong();
        long availableBlocks = stat.getAvailableBlocksLong();
        return formatSize(availableBlocks * blockSize);
}

public static String formatSize(long size) {
    String suffix = null;

    if (size >= 1024) {
        suffix = "KB";
        size /= 1024;
        if (size >= 1024) {
            suffix = "MB";
            size /= 1024;
        }
    }

    StringBuilder resultBuffer = new StringBuilder(Long.toString(size));

    int commaOffset = resultBuffer.length() - 3;
    while (commaOffset > 0) {
        resultBuffer.insert(commaOffset, ',');
        commaOffset -= 3;
    }

    if (suffix != null) resultBuffer.append(suffix);
    return resultBuffer.toString();
}
Anand jain
  • 89
  • 5