Android Kotlin: Getting a FileNotFoundException with filename chosen from file picker?

后端 未结 3 931
眼角桃花
眼角桃花 2020-11-22 01:13

I\'m working on an Android application where one of the features is to let the user choose a file to open (I\'m wanting to open a plain text .txt file). I\'ve worked on And

3条回答
  •  情深已故
    2020-11-22 01:32

    You cannot open a Java File on a ÙRI converted to a String, the "path" section of the URI has no relation to a physical file location.

    Use a contentResolver to get a Java FileDescriptor to open the file with.

    val parcelFileDescriptor: ParcelFileDescriptor =
                contentResolver.openFileDescriptor(uri, "r")
        val fileDescriptor: FileDescriptor = parcelFileDescriptor.fileDescriptor
    

    This method is compatible with Android 10 where file paths for non App private directories are not usuable.

    https://developer.android.com/training/data-storage/shared/documents-files

提交回复
热议问题