儲存裝置經格式化後劃分為固定大小的區塊。檔案佔用空間以區塊為單位 (如 4KB),即使檔案只有 1 Byte 也佔 1 區塊。
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;
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;
}
}
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);
getExternalStorageDirectory() 回傳的路徑在分區儲存下可能受限。context.getExternalFilesDirs(null) 取得 App 專屬外部目錄 (免權限),再對各目錄查詢 StatFs。getAvailableBlocksLong(),實際可用可能略大於此值。