萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> Android 開發

Android 獲取內部/外部儲存空間大小:StatFs 與 Formatter 實用工具類

儲存區塊概念

儲存裝置經格式化後劃分為固定大小的區塊。檔案佔用空間以區塊為單位 (如 4KB),即使檔案只有 1 Byte 也佔 1 區塊。

核心 API:StatFs

StatFs stat = new StatFs(path);
long blockSize = stat.getBlockSizeLong();       // 區塊大小 (bytes)
long totalBlocks = stat.getBlockCountLong();    // 總區塊數
long availBlocks = stat.getAvailableBlocksLong(); // 可用區塊數 (應用可用)
long freeBlocks = stat.getFreeBlocksLong();     // 物理剩餘區塊數 (含系統保留)

long totalBytes = blockSize * totalBlocks;
long availBytes = blockSize * availBlocks;

人類可讀格式化:Formatter

String totalStr = Formatter.formatFileSize(context, totalBytes); // 如 "12.5 GB"
String availStr = Formatter.formatFileSize(context, availBytes); // 如 "3.2 GB"

完整工具類

public class StorageUtils {
    public static class StorageInfo {
        public long totalBytes, availableBytes;
        public String totalStr, availableStr;
    }

    /** 取得外部儲存 (SD 卡/共享儲存) 資訊 */
    public static StorageInfo getExternalStorageInfo(Context ctx) {
        StorageInfo info = new StorageInfo();
        if (!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            return info; // 不可用
        }
        File path = Environment.getExternalStorageDirectory();
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSizeLong();
        info.totalBytes = blockSize * stat.getBlockCountLong();
        info.availableBytes = blockSize * stat.getAvailableBlocksLong();
        info.totalStr = Formatter.formatFileSize(ctx, info.totalBytes);
        info.availableStr = Formatter.formatFileSize(ctx, info.availableBytes);
        return info;
    }

    /** 取得內部儲存 (App 數據分區) 資訊 */
    public static StorageInfo getInternalStorageInfo(Context ctx) {
        StorageInfo info = new StorageInfo();
        File path = Environment.getDataDirectory(); // /data
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSizeLong();
        info.totalBytes = blockSize * stat.getBlockCountLong();
        info.availableBytes = blockSize * stat.getAvailableBlocksLong();
        info.totalStr = Formatter.formatFileSize(ctx, info.totalBytes);
        info.availableStr = Formatter.formatFileSize(ctx, info.availableBytes);
        return info;
    }
}

Activity 中顯示

TextView tvExternal = findViewById(R.id.tv_external);
TextView tvInternal = findViewById(R.id.tv_internal);

StorageInfo ext = StorageUtils.getExternalStorageInfo(this);
StorageInfo intl = StorageUtils.getInternalStorageInfo(this);

tvExternal.setText("外部儲存\n總計:" + ext.totalStr + "\n可用:" + ext.availableStr);
tvInternal.setText("內部儲存\n總計:" + intl.totalStr + "\n可用:" + intl.availableStr);

Android 10+ (API 29) 注意事項

  • getExternalStorageDirectory() 回傳的路徑在分區儲存下可能受限。
  • 建議改用 context.getExternalFilesDirs(null) 取得 App 專屬外部目錄 (免權限),再對各目錄查詢 StatFs。
  • 系統保留空間不計入 getAvailableBlocksLong(),實際可用可能略大於此值。

效果截圖

儲存空間顯示效果
copyright © 萬盛學電腦網 all rights reserved