获取手机的内部总容量和可用容量:
File path = Environment.getDataDirrectory();//获取手机的/data目录
StatFs stat = new StatFs(path.getPath());//获取文件系统的状态
long blockSize = stat.getBlockSize();//每个block 占字节数
long availableBlocks = stat.getAvailableBlocks();//可用的block占字节数
long totalBlocks = stat.getBlockCount();//block总数
long totalSize = blockSize * totalBlocks;//得到总共占字节数
long availableSize = blockSize * availableBlocks;//得到可用占字节数
String totalSizeStr = Formatter.formatFileSize(this, totalSize);//将总共占字节数格式化为字符串形式
String availableSizeStr = Formatter.formatFileSize(this, availableSize);//将总共占字节数格式化为字符串形式
获取SD卡总容量和可用容量(方法同获取手机内部容量一样,仅获取的文件目录不一样):
File path = Environment.getExternalStorageDirectory();//获取/storage/sdcard目录即获取SD卡的根目录
StatFs stat = new StatFs(path.getPath());//获取文件系统的状态
long blockSize = stat.getBlockSize();//每个block 占字节数
long availableBlocks = stat.getAvailableBlocks();//可用的block占字节数
long totalBlocks = stat.getBlockCount();//block总数
long totalSize = blockSize * totalBlocks;//得到总共占字节数
long availableSize = blockSize * availableBlocks;//得到可用占字节数
String totalSizeStr = Formatter.formatFileSize(this, totalSize);//将总共占字节数格式化为字符串形式
String availableSizeStr = Formatter.formatFileSize(this, availableSize);//将总共占字节数格式化为字符串形式
注意:
访问SDCard进行文件读写时:
在AndroidManifest.xml中加入访问SDCard的权限如下:
<!-- 在SDCard中创建与删除文件权限 -->
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<!-- 往SDCard写入数据权限 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>