Android 内存卡 / Micro SD 卡 / TF 卡 / 存储卡 剩余容量 / 剩余内存 / 可用空间、总容量的 2 种获取方式

版权声明:本文为【路易斯】原创文章,转载请注明出处! https://blog.csdn.net/RichieZhu/article/details/79872953

1 采用 Java 的 File 类

// 总容量
    public long getStorageTotalSpace(String path) {
        File file = new File(path);
        return file.getTotalSpace();
    }
// 可用容量
    public long getStorageAvailableSpace(String path) {
        File file = new File(path);
        // getUsableSpace 比  getFreeSpace 准确
        return file.getUsableSpace();
    }

2 采用 Android 的 StatFs 类

// 总容量
public long getStorageTotalSpace(String path) {
        StatFs statFs = new StatFs(path);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            return statFs.getTotalBytes();
        } else {
            return statFs.getBlockSizeLong() * statFs.getBlockCountLong();
        }
    }
// 可用容量
    public long getStorageAvailableSpace(String path) {
         StatFs statFs = new StatFs(path);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            // getAvailableBytes 比 getFreeBytes 准确
            return statFs.getAvailableBytes();
        } else {
            // getAvailableBlocksLong 比 getFreeBlocksLong 准确
            return statFs.getBlockSizeLong() * statFs.getAvailableBlocksLong();
        }

模拟器测试:

这里写图片描述

这里写图片描述

真机测试:

这里写图片描述
ES 文件浏览器 显示的是【已用容量 / 总容量】,另外小数可能会有误差

这里写图片描述

猜你喜欢

转载自blog.csdn.net/RichieZhu/article/details/79872953