Search code examples
androidsaving-dataandroid-internal-storage

Checking if the storage is full before writing to internal storage


I use internal data (the app's private data) to save data.

However, in the event that the device is out of storage, how can I check if the storage is full before saving? And in the event the data written to the file is very big, causing the device's storage to become full, how can I check this and notify the user/prevent the app from showing the force close dialog?

Does the Android system do anything on this issue(e.g. show a message that tells the user there isn't more space on the device)?

The main concern is making sure the check happens on the applicable drive; if the app has been moved to an SD card or some other external storage unit, that is the drive that should be checked against in terms of remaining memory

Example scenario: The device has 238KB left. There are 10 files that data is saved to. Each file is 30-40KB. Assuming the average is 35KB/file, 6 files can be written, while the last 4 cannot. How can I handle issues such as this?


Solution

  • You have asked several questions, but all you need to do is a simple check to see if there is available storage memory before proceeding with any file write operation.

    You can use this utility method to quickly check for free storage space on the device,

     public static long getAvailableInternalMemorySize() {
            File path = Environment.getDataDirectory();
            StatFs stat = new StatFs(path.getPath());
            long blockSize, availableBlocks;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
                blockSize = stat.getBlockSizeLong();
                availableBlocks = stat.getAvailableBlocksLong();
            } else {
                blockSize = stat.getBlockSize();
                availableBlocks = stat.getAvailableBlocks();
            }
            return availableBlocks * blockSize;
        }
    

    As you know you can get the size of your files using the length() method of the files. It will return you the size of each file in bytes.

    All you need to do is compare the size of the files you intend to write with the available storage memory. If the size of your files is less than the total storage available, you can go ahead and write your files.