我正在使用Environment.getExternalStorageDirectory()创建一个文件,在创建和存储文件之前,我需要知道是否有足够的可用空间。
如果你能引用Android Ref文档,那也会有所帮助。
答案 0 :(得分:6)
您必须使用StatFs类。以下是从源代码到手机上的“设置”应用程序中使用它的示例。
if (status.equals(Environment.MEDIA_MOUNTED)) {
try {
File path = Environment.getExternalStorageDirectory();
StatFs stat = new StatFs(path.getPath());
long blockSize = stat.getBlockSize();
long totalBlocks = stat.getBlockCount();
long availableBlocks = stat.getAvailableBlocks();
mSdSize.setSummary(formatSize(totalBlocks * blockSize));
mSdAvail.setSummary(formatSize(availableBlocks * blockSize) + readOnly);
mSdMountToggle.setEnabled(true);
mSdMountToggle.setTitle(mRes.getString(R.string.sd_eject));
mSdMountToggle.setSummary(mRes.getString(R.string.sd_eject_summary));
} catch (IllegalArgumentException e) {
// this can occur if the SD card is removed, but we haven't received the
// ACTION_MEDIA_REMOVED Intent yet.
status = Environment.MEDIA_REMOVED;
}
答案 1 :(得分:2)
使用StatFS
。如果您将值从Environment.getExternalStorageDirectory()
传递给构造函数(当然转换为String
),它应该可以工作。
答案 2 :(得分:1)
您可能需要重新安排才能获得准确的结果:
StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getAbsolutePath());
stat.restat(Environment.getExternalStorageDirectory().getAbsolutePath());
long available = ((long) stat.getAvailableBlocks() * (long) stat.getBlockSize());
答案 3 :(得分:0)
自API级别9起可用:
Environment.getExternalStorageDirectory().getUsableSpace();
http://developer.android.com/reference/java/io/File.html#getUsableSpace()