標籤:
SD 記憶卡相關的輔助類:
1、判斷 SDCard 是否可用;
2、擷取 SD 記憶卡路徑;
3、擷取 SD 記憶卡的剩餘容量,單位 byte;
4、擷取指定路徑所在空間的剩餘可用容量位元組數,單位byte;
5、擷取系統儲存路徑;
1 import java.io.File; 2 import android.os.Environment; 3 import android.os.StatFs; 4 5 // SD卡相關的輔助類 6 public class SDCardUtils 7 { 8 private SDCardUtils() 9 {10 /* cannot be instantiated */11 throw new UnsupportedOperationException("cannot be instantiated");12 }13 14 /**15 * 判斷 SDCard 是否可用16 * 17 * @return18 */19 public static boolean isSDCardEnable()20 {21 return Environment.getExternalStorageState().equals(22 Environment.MEDIA_MOUNTED);23 24 }25 26 /**27 * 擷取 SD 記憶卡路徑28 * 29 * @return30 */31 public static String getSDCardPath()32 {33 return Environment.getExternalStorageDirectory().getAbsolutePath()34 + File.separator;35 }36 37 /**38 * 擷取 SD 記憶卡的剩餘容量, 單位 byte39 * 40 * @return41 */42 public static long getSDCardAllSize()43 {44 if (isSDCardEnable())45 {46 StatFs stat = new StatFs(getSDCardPath());47 // 擷取閒置資料區塊的數量48 long availableBlocks = (long) stat.getAvailableBlocks() - 4;49 // 擷取單個資料區塊的大小(byte)50 long freeBlocks = stat.getAvailableBlocks();51 return freeBlocks * availableBlocks;52 }53 return 0;54 }55 56 /**57 * 擷取指定路徑所在空間的剩餘可用容量位元組數,單位byte58 * 59 * @param filePath60 * @return 容量位元組 SDCard可用空間,內部儲存可用空間61 */62 public static long getFreeBytes(String filePath)63 {64 // 如果是sd卡的下的路徑,則擷取sd卡可用容量65 if (filePath.startsWith(getSDCardPath()))66 {67 filePath = getSDCardPath();68 } else69 {// 如果是內部儲存的路徑,則擷取記憶體儲存的可用容量70 filePath = Environment.getDataDirectory().getAbsolutePath();71 }72 StatFs stat = new StatFs(filePath);73 long availableBlocks = (long) stat.getAvailableBlocks() - 4;74 return stat.getBlockSize() * availableBlocks;75 }76 77 /**78 * 擷取系統儲存路徑79 * 80 * @return81 */82 public static String getRootDirectoryPath()83 {84 return Environment.getRootDirectory().getAbsolutePath();85 }86 87 }
Android 開發工具類 08_SDCardUtils