Question

I am using Environment.getExternalStorageDirectory() to create a file and I will need to know if there is enough space available before I create and store the file.

If you can cite the Android Ref doc, that would be helpful too.

Was it helpful?

Solution

You have to use the StatFs Class. Here is an example of how to use it taken from the source code to the Settings application found on the phone.

        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;
        }

OTHER TIPS

Use StatFS. It should work if you pass in the value from Environment.getExternalStorageDirectory() to the constructor (converting to String, of course).

You may have to restat to get accurate results:

StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getAbsolutePath());
stat.restat(Environment.getExternalStorageDirectory().getAbsolutePath());
long available = ((long) stat.getAvailableBlocks() * (long) stat.getBlockSize());

Usable since API level 9:

Environment.getExternalStorageDirectory().getUsableSpace();

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top