内部存储空间
我们知道,存储硬件的空间是按着区块来划分的,每个区块有固定的大小。存储设备的总大小=区块大小*区块数量。通过StatFs类,我们可以获取到总的区块,可用区块和每个区块的字节大小等信息。
/**
* 获取手机内部空间总大小
*
* @return 大小,字节为单位
*/
static public long getTotalInternalMemorySize() {
//获取内部存储根目录
File path = Environment.getDataDirectory();
//系统的空间描述类
StatFs stat = new StatFs(path.getPath());
//每个区块占字节数
long blockSize = stat.getBlockSize();
//区块总数
long totalBlocks = stat.getBlockCount();
return totalBlocks * blockSize;
}
/**
* 获取手机内部可用空间大小
*
* @return 大小,字节为单位
*/
static public long getAvailableInternalMemorySize() {
File path = Environment.getDataDirectory();
StatFs stat = new StatFs(path.getPath());
long blockSize = stat.getBlockSize();
//获取可用区块数量
long availableBlocks = stat.getAvailableBlocks();
return availableBlocks * blockSize;
}
用以上两个方法,就可以获得内部存储空间总大小和可用大小了。
sdcard外部存储空间
/**
* 判断SD卡是否可用
*
* @return true : 可用<br>false : 不可用
*/
public static boolean isSDCardEnable() {
return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
}
/**
* 获取手机外部总空间大小
*
* @return 总大小,字节为单位
*/
static public long getTotalExternalMemorySize() {
if (isSDCardEnable()) {
//获取SDCard根目录
File path = Environment.getExternalStorageDirectory();
StatFs stat = new StatFs(path.getPath());
long blockSize = stat.getBlockSize();
long totalBlocks = stat.getBlockCount();
return totalBlocks * blockSize;
} else {
return -1;
}
}
/**
* 获取SD卡剩余空间
*
* @return SD卡剩余空间
*/
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
public static String getFreeSpace() {
if (!isSDCardEnable()) return "sdcard unable!";
StatFs stat = new StatFs(getSDCardPath());
long blockSize, availableBlocks;
availableBlocks = stat.getAvailableBlocksLong();
blockSize = stat.getBlockSizeLong();
long size = availableBlocks * blockSize / 1024L;
return String.valueOf(size);
}
统一描述sdcard的信息
/**
* 获取SD卡信息
*
* @return SDCardInfo
*/
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
public static String getSDCardInfo() {
SDCardInfo sd = new SDCardInfo();
if (!isSDCardEnable()) return "sdcard unable!";
sd.isExist = true;
StatFs sf = new StatFs(Environment.getExternalStorageDirectory().getPath());
sd.totalBlocks = sf.getBlockCountLong();
sd.blockByteSize = sf.getBlockSizeLong();
sd.availableBlocks = sf.getAvailableBlocksLong();
sd.availableBytes = sf.getAvailableBytes();
sd.freeBlocks = sf.getFreeBlocksLong();
sd.freeBytes = sf.getFreeBytes();
sd.totalBytes = sf.getTotalBytes();
return sd.toString();
}
public static class SDCardInfo {
boolean isExist;
long totalBlocks;
long freeBlocks;
long availableBlocks;
long blockByteSize;
long totalBytes;
long freeBytes;
long availableBytes;
@Override
public String toString() {
return "isExist=" + isExist +
"\ntotalBlocks=" + totalBlocks +
"\nfreeBlocks=" + freeBlocks +
"\navailableBlocks=" + availableBlocks +
"\nblockByteSize=" + blockByteSize +
"\ntotalBytes=" + totalBytes +
"\nfreeBytes=" + freeBytes +
"\navailableBytes=" + availableBytes;
}
}