Android: How to check IOException cause when drive is out of space

Viewed 730

How to check IOException cause on the catch?

Is e.getCause().getMessage() always returns the same string on all the android versions and devices for the same cause? Is it a good approach to check if IOException's cause is android.system.ErrnoException: write failed: ENOSPC (No space left on device) for checking if the user's device is out of space on that specific drive?

try {
    // Here I'm writing a file with OutputStream
} catch (IOException e) {
    // Check if IOException cause equals android.system.ErrnoException: write failed: ENOSPC (No space left on device)
} finally {

}
1 Answers

It is not usually a good idea to rely on error messages as they might vary with OS versions. If targeting API level 21 or above, there is an elegant way to find the actual root cause of the IOException based on an error code. (ENOSPC in your case) https://developer.android.com/reference/android/system/OsConstants#ENOSPC

It may be checked like this:

catch (IOException e) {
    if (e.getCause() instanceof ErrnoException) { 
        int errorNumber = ((ErrnoException) e.getCause()).errno;
        if (errorNumber == OsConstants.ENOSPC) {
            // Out of space
        }
    }
}

errno is a public field in https://developer.android.com/reference/android/system/ErrnoException

Related