如何获得 SD 卡大小?

How can I get SD-Card size?

我想获取 SD 卡(可移动)和内部内存的大小。我使用两种方法。但是他们两个return我的InternalMemory大小。

内部内存大小的方法:

public static String getTotalInternalMemorySize() {

    File path = Environment.getDataDirectory();
    StatFs stat = new StatFs(path.getPath());
    long blockSize = stat.getBlockSize();
    long totalBlocks = stat.getBlockCount();
    return formatSize(totalBlocks * blockSize);

}

SD卡大小计算方法:

public static String getTotalExternalMemorySize() {
  
    File path = Environment.getExternalStorageDirectory();
    StatFs stat = new StatFs(path.getPath());
    long blockSize = stat.getBlockSize();
    long totalBlocks = stat.getBlockCount();
    return formatSize(totalBlocks * blockSize);
 
}

用户可读格式的格式化方法:

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

如何获取 SD 卡大小?

使用 getExternalFilesDirs() 返回的第二项。