如何获得android中的可用空间

时间:2018-06-02 07:07:57

标签: android

我使用以下方法查找外部和内部目录的可用/可用空间。内部存储器返回4 GB,外部存储器返回3.9 GB。但是,当我进入手机的故事部分时,它显示了3.7 GB的可用空间。为什么会出现这种不匹配现象。

 long freeBytesInternal = new File(ctx.getFilesDir().getAbsoluteFile().toString()).getFreeSpace();
   long freeBytesExternal = new File(ctx.getExternalFilesDir(null).toString()).getFreeSpace();

1 个答案:

答案 0 :(得分:0)

要查找可用的内存大小: -

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();
}