Android/Java Get Filename of URI or Path

Sep 25, 2019

Get filename from string path

val path = "/storage/emulated/0/DCIM/Camera/20190221_181813.jpg"val filename = File(path).name

Get filename from uri

val path = "/storage/emulated/0/DCIM/Camera/20190221_181813.jpg"val uri = Uri.parse(path)val filename = File(uri.path).name

NOTE: This only works if uri.scheme == ContentResolver.SCHEME_FILE.

Get filename from uri (support SCHEME_CONTENT and SCHEME_FILE)

fun getFilename(contentResolver: ContentResolver, uri: Uri): String? {    return when(uri.scheme) {        ContentResolver.SCHEME_CONTENT -> {            contentResolver.query(uri, null, null, null, null)?.use { cursor ->                val nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)                cursor.getString(nameIndex);            }        }        ContentResolver.SCHEME_FILE-> {            uri.path?.let { path ->                File(path).name            }        }        else -> null    }}

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.