通过 df 指令可查看当前文件系统的磁盘空间占用情况:
方法一:
private long getSDCardAvailSize() { String state = Environment.getExternalStorageState(); long aaa=0; if (Environment.MEDIA_MOUNTED.equals(state)) { File sdcardDir = Environment.getExternalStorageDirectory(); StatFs sf = new StatFs(sdcardDir.getPath()); long blockSize = sf.getBlockSize(); long blockCount = sf.getBlockCount(); long availCount = sf.getAvailableBlocks(); long totalSeize = blockSize * blockCount; aaa = availCount * blockSize; Log.e("size", "block大小:" + blockSize + ",block数目:" + blockCount + ",总大小:" + blockSize * blockCount / 1024 + "KB"); Log.e("size", "可用的block数目::" + availCount + ",剩余空间:" + availCount * blockSize / 1024 + "KB"); } return aaa; }
方法二:
public long getSystemAvailableStorage() throws RemoteException { try { StorageStatsManager stats = mContext.getSystemService(StorageStatsManager.class); return stats.getFreeBytes(StorageManager.UUID_DEFAULT)/1024/1024; } catch (NoSuchFieldError | NoClassDefFoundError | NullPointerException | IOException e) { e.printStackTrace(); return -1; } }
方法三:
File datapath = Environment.getDataDirectory(); StatFs dataFs=new StatFs(datapath.getPath()); long sizes=(long)dataFs.getFreeBlocks()*(long)dataFs.getBlockSize(); long available=sizes/((1024*1024));
补充:该方法获取当前Emmc总大小:
public long getSystemTotalStorage() throws RemoteException { try { long iTotalSize = -1; FileInputStream fis = new FileInputStream(new File("/proc/partitions")); BufferedReader br = new BufferedReader(new InputStreamReader(fis)); String Line = ""; while ((Line = br.readLine()) != null) { if (Line.length() > 7 && Line.lastIndexOf(" ") > 0) { if (Line.substring(Line.lastIndexOf(" ") + 1 , Line.length()).equals("mmcblk0")) { int lastSpacePos = Line.lastIndexOf(" "); String sOnlyNumber = Line.substring(0, lastSpacePos-1); int lastSpaceBeforeSize = sOnlyNumber.lastIndexOf(" "); String sTotalSize = Line.substring(lastSpaceBeforeSize+1, lastSpacePos); Log.d(TAG, "sTotalSize = " + sTotalSize); iTotalSize = Long.parseLong(sTotalSize)/1024; break; } } } br.close(); return iTotalSize; } catch (IOException e) { e.printStackTrace(); } return -1; }