转自 http://blog.163.com/hero_213/blog/static/39891214201162123236660/
该代码片段可以让我们获取internal和external的存储空间大小。
import java.io.File;
import android.os.Environment;
import android.os.StatFs;
public class StorageUtil {
private static final int ERROR = -1;
/**
* SDCARD是否存
*/
public static boolean externalMemoryAvailable() {
return android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED);
}
/**
* 获取手机内部剩余存储空间
* @return
*/
public static long getAvailableInternalMemorySize() {
File path = Environment.getDataDirectory();
StatFs stat = new StatFs(path.getPath());
long blockSize = stat.getBlockSize();
long availableBlocks = stat.getAvailableBlocks();
return availableBlocks * blockSize;
}
/**
* 获取手机内部总的存储空间
* @return
*/
public static long getTotalInternalMemorySize() {
File path = Environment.getDataDirectory();
StatFs stat = new StatFs(path.getPath());
long blockSize = stat.getBlockSize();
long totalBlocks = stat.getBlockCount();
return totalBlocks * blockSize;
}
/**
* 获取SDCARD剩余存储空间
* @return
*/
public static 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 ERROR;
}
}
/**
* 获取SDCARD总的存储空间
* @return
*/
public static 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 ERROR;
}
}
}
1.硬件上的 block size, 应该是"sector size",linux的扇区大小是512byte
2.有文件系统的分区的block size, 是"block size",大小不一,可以用工具查看
3.没有文件系统的分区的block size,也叫“block size”,大小指的是1024 byte
4.Kernel buffer cache 的block size, 就是"block size",大部分PC是1024
5.磁盘分区的"cylinder size",用fdisk 可以查看。
我们这里的block size是第二种情况,一般SD卡都是fat32的文件系统,block size是4096.
这样就可以知道手机的内部存储空间和sd卡存储空间的总大小和可用大小了