Android獲取內建SD卡的大小
阿新 • • 發佈:2019-01-08
廢話不多說,先上程式碼:
/** * 獲取手機內部空間大小 * @return */ public static double getTotalInternalStorgeSize() { File path = Environment.getExternalStorageDirectory(); StatFs mStatFs = new StatFs(path.getPath()); long blockSize = mStatFs.getBlockSize(); long totalBlocks = mStatFs.getBlockCount(); DecimalFormat df = new DecimalFormat("#.00"); // 這裡忽略至小數點後兩位,不做四捨五入 return Double.valueOf(df.format(((totalBlocks * blockSize) / 1024.0 / 1024.0 / 1024.0))); } /** * 獲取手機內部可用空間大小 * @return */ public static double getAvailableInternalStorgeSize() { File path = Environment.getExternalStorageDirectory(); StatFs mStatFs = new StatFs(path.getPath()); long blockSize = mStatFs.getBlockSize(); long availableBlocks = mStatFs.getAvailableBlocks(); DecimalFormat df = new DecimalFormat("#.00"); // 這裡忽略至小數點後兩位,不做四捨五入 return Double.valueOf(df.format(((availableBlocks * blockSize) / 1024.0 / 1024.0 / 1024.0))); }
網上搜的很多文章發現計算出來的儲存空間大小總是偏大,經過一位大神的指點發現是檔案的路徑有問題,網上搜的很多文章的檔案路徑為:
// 這個路徑下可能存有系統某些檔案,導致計算獲得的儲存空間偏大
String path=Environment.getDataDirectory();
而注意上面我寫的程式碼,檔案路徑為:
File path = Environment.getExternalStorageDirectory();