How to check availability of space on external storage?

后端 未结 6 1689
无人及你
无人及你 2021-01-08 00:24

How do you check if the SD card is full or not so that your application can decide if it can continue to do its job i.e. write to external storage or notify the user that st

6条回答
  •  一生所求
    2021-01-08 01:01

    Watch out with StatFs & int overflow on newer devices

    The approach in this answer is broken on devices with large external storage. For example on my Nexus 7, it currently returns ~2 GB when in reality there is ~10 GB of space left.

    // DOES NOT WORK CORRECTLY ON DEVICES WITH LARGE STORAGE DUE TO INT OVERFLOW
    File externalStorageDir = Environment.getExternalStorageDirectory();
    StatFs statFs = new StatFs(externalStorageDirectory.getAbsolutePath());  
    int free = (statFs.getAvailableBlocks() * statFs.getBlockSize()) / 1024 / 1024;
    

    StatFs does have replacement methods returning long, getAvailableBlocksLong() and getBlockCountLong(), but the problem is that they were only added in API level 18.

    Use this instead

    Simplest way is to use getFreeSpace() in java.io.File, added in API level 9, which returns long:

    Returns the number of free bytes on the partition containing this path. Returns 0 if this path does not exist.

    So, to get free space on the external storage ("SD card"):

    File externalStorageDir = Environment.getExternalStorageDirectory();
    long free = externalStorageDir.getFreeSpace() / 1024 / 1024;
    

    Alternatively, if you really want to use StatFs but need to support API level < 18, this would fix the integer overflow:

    File externalStorageDir = Environment.getExternalStorageDirectory();
    StatFs statFs = new StatFs(externalStorageDir.getAbsolutePath());  
    long blocks = statFs.getAvailableBlocks();
    long free = (blocks * statFs.getBlockSize()) / 1024 / 1024;
    

提交回复
热议问题