3 回答
TA贡献1805条经验 获得超10个赞
试试这个代码:
StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
long bytesAvailable = (long)stat.getBlockSize() *(long)stat.getBlockCount();
long megAvailable = bytesAvailable / 1048576;
System.out.println("Megs :"+megAvailable);
更新:
getBlockCount() -SD卡的返回大小;
getAvailableBlocks() -返回普通程序仍可访问的块数(感谢乔)
TA贡献1860条经验 获得超8个赞
Yaroslav的答案将给出SD卡的大小,而不是可用空间。StatFs getAvailableBlocks()将返回普通程序仍可访问的块数。这是我正在使用的功能:
public static float megabytesAvailable(File f) {
StatFs stat = new StatFs(f.getPath());
long bytesAvailable = (long)stat.getBlockSize() * (long)stat.getAvailableBlocks();
return bytesAvailable / (1024.f * 1024.f);
}
上面的代码引用了一些不推荐使用的功能。下面我复制一个更新的版本:
public static float megabytesAvailable(File f) {
StatFs stat = new StatFs(f.getPath());
long bytesAvailable = 0;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR2)
bytesAvailable = (long) stat.getBlockSizeLong() * (long) stat.getAvailableBlocksLong();
else
bytesAvailable = (long) stat.getBlockSize() * (long) stat.getAvailableBlocks();
return bytesAvailable / (1024.f * 1024.f);
}
TA贡献1829条经验 获得超7个赞
我设计了一些现成的函数来获取不同单位的可用空间。您可以通过简单地将其中任何一种复制到项目中来使用这些方法。
/**
* @return Number of bytes available on External storage
*/
public static long getAvailableSpaceInBytes() {
long availableSpace = -1L;
StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
availableSpace = (long) stat.getAvailableBlocks() * (long) stat.getBlockSize();
return availableSpace;
}
/**
* @return Number of kilo bytes available on External storage
*/
public static long getAvailableSpaceInKB(){
final long SIZE_KB = 1024L;
long availableSpace = -1L;
StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
availableSpace = (long) stat.getAvailableBlocks() * (long) stat.getBlockSize();
return availableSpace/SIZE_KB;
}
/**
* @return Number of Mega bytes available on External storage
*/
public static long getAvailableSpaceInMB(){
final long SIZE_KB = 1024L;
final long SIZE_MB = SIZE_KB * SIZE_KB;
long availableSpace = -1L;
StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
availableSpace = (long) stat.getAvailableBlocks() * (long) stat.getBlockSize();
return availableSpace/SIZE_MB;
}
/**
* @return Number of gega bytes available on External storage
*/
public static long getAvailableSpaceInGB(){
final long SIZE_KB = 1024L;
final long SIZE_GB = SIZE_KB * SIZE_KB * SIZE_KB;
long availableSpace = -1L;
StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
availableSpace = (long) stat.getAvailableBlocks() * (long) stat.getBlockSize();
return availableSpace/SIZE_GB;
}
添加回答
举报