3

我正在使用 Environment.getExternalStorageDirectory() 创建文件,在创建和存储文件之前,我需要知道是否有足够的可用空间。

如果您可以引用 Android Ref 文档,那也会很有帮助。

4

4 回答 4

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;
        }
于 2010-09-10T18:07:34.877 回答
2

使用StatFS. 如果您将值 fromEnvironment.getExternalStorageDirectory()传递给构造函数(当然转换为String),它应该可以工作。

于 2010-09-10T17:57:34.783 回答
1

您可能需要重新统计才能获得准确的结果:

StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getAbsolutePath());
stat.restat(Environment.getExternalStorageDirectory().getAbsolutePath());
long available = ((long) stat.getAvailableBlocks() * (long) stat.getBlockSize());
于 2010-12-02T18:37:46.650 回答
0

从 API 级别 9 开始可用:

Environment.getExternalStorageDirectory().getUsableSpace();

http://developer.android.com/reference/java/io/File.html#getUsableSpace()

于 2014-06-13T09:32:56.033 回答