How to extract the file name from URI returned from Intent.ACTION_GET_CONTENT?

后端 未结 17 2081
梦如初夏
梦如初夏 2020-11-28 05:09

I am using 3rd party file manager to pick a file (PDF in my case) from the file system.

This is how I launch the activity:

Intent i         


        
17条回答
  •  星月不相逢
    2020-11-28 06:10

    For Kotlin, You can use something like this :

    object FileUtils {
    
       fun Context.getFileName(uri: Uri): String?
            = when (uri.scheme) {
                ContentResolver.SCHEME_FILE -> File(uri.path).name
                ContentResolver.SCHEME_CONTENT -> getCursorContent(uri)
                else -> null
            }
    
        private fun Context.getCursorContent(uri: Uri): String? 
            = try {
                contentResolver.query(uri, null, null, null, null)?.let { cursor ->
                    cursor.run {
                        if (moveToFirst()) getString(getColumnIndex(OpenableColumns.DISPLAY_NAME))
                        else null
                    }.also { cursor.close() }
                }
            } catch (e : Exception) { null }
    

提交回复
热议问题