android StatFs类

StatFs类,一个模拟linux的df命令的类,成员函数是获得底层Linux文件系统的属性函数。StatFs 常用方法:

       A,getAvailableBlocks(),返回Int,获取当前系统可用存储空间的Block数。

       B,getBlockCount(),返回Int,获取当前系统存储空间总的Block数。

       C,getBlockSize(),返回Int ,获取当前系统Block占的大小,以字节为单位

       D,getFreeBlocks(),返回Int ,该块区域剩余的空间(包括可用空间和保留空间)。

代码

一个获取系统和SD卡可用容量及总总量的实例

import android.os.Environment;
import android.os.StatFs;
import java.io.File;
public long getAvailableInternalMemorySize(){
          File path = Environment.getDataDirectory();  
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSize();
        long availableBlocks = stat.getAvailableBlocks();
        return availableBlocks*blockSize;
}
    
public long getTotalInternalMemorySize(){
        File path = Environment.getDataDirectory();
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSize();
        long totalBlocks = stat.getBlockCount();
        return totalBlocks*blockSize;
}
    
public boolean externalMemoryAvailable(){
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
}
    
public long getAvailableExternalMemorySize(){
        if(externalMemoryAvailable()){
            File path = Environment.getExternalStorageDirectory();
            StatFs stat = new StatFs(path.getPath());
            long blockSize = stat.getBlockSize();
            long availableBlocks = stat.getAvailableBlocks();
            return availableBlocks*blockSize;
        }
        else{
            return -1;
        }
}
    
public long getTotalExternalMemorySize(){
        if(externalMemoryAvailable()){
            File path = Environment.getExternalStorageDirectory();
            StatFs stat = new StatFs(path.getPath());
            long blockSize = stat.getBlockSize();
            long totalBlocks = stat.getBlockCount();
            return totalBlocks*blockSize;
        }
        else{
            return -1;
        }
}
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

 从LOG输出数据即可,以M为单位。

        Log.i("zhangcheng","内部可用存储空间是:"+Long.toString(getAvailableInternalMemorySize()/(1024*1024)));
        Log.i("zhangcheng","内部总共存储空间是:"+Long.toString(getTotalInternalMemorySize()/(1024*1024)));
        
        Log.i("zhangcheng","外部可用存储空间是:"+Long.toString(getAvailableExternalMemorySize()/(1024*1024)));
        Log.i("zhangcheng","外部总共存储空间是:"+Long.toString(getTotalExternalMemorySize()/(1024*1024)));  

 

posted @ 2015-12-08 10:38  weidingqiang  阅读(427)  评论(0)    收藏  举报