Android Scope Storage: Check Uri Exist

January 30, 2020

Assuming you have the media/file uri based on MediaStore.MediaColumns._ID.

Solution 1

Use MediaFile.

val file = DocumentFile.fromSingleUri(context, uri)
if (file == null) {
    Timber.d("File not found: $uri")
}

Solution 2

Try to open file via ContentResolver.openInputStream

val isExist = try {
    context.contentResolver.openInputStream(uri)?.use {

    }
    true
}
catch (e: IOException) {
    false
}

DocumentFile.exists() doesn’t work

DocumentFile.exists() return false even though ContentResolver.openInputStream succeed.

val file = DocumentFile.fromSingleUri(context, uri)
if (file != null) {
    Timber.d("File exists: ${file.exists()}")
}
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.