sheldon_blogs

Android : 获取内部存储信息方法总结

  通过 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;
        }
    }

方法三:

    //获取可用存储大小,data区的剩余空间,返回字节数public long getAvailableInternalSize() {
        File path = Environment.getDataDirectory();
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSize();
        long availableBlocks = stat.getAvailableBlocks();
        return availableBlocks * blockSize;
    }

 

补充:该方法获取当前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;
    }

 

posted on 2020-03-19 11:15  sheldon_blogs  阅读(1820)  评论(0编辑  收藏  举报

导航