How can I read File from MediaStore in Relative Path?

Viewed 2208

In Android 10 or higher, I used MediaStore to save files in Downloads, shared storage. The code I used to save the file is as follows:

        GlobalScope.launch {
        val values = ContentValues().apply {
            put(MediaStore.Downloads.DISPLAY_NAME, "file.txt")
            put(MediaStore.Downloads.MIME_TYPE, "text/plain")
            put(MediaStore.Downloads.IS_PENDING, 1)
            put(MediaStore.Downloads.RELATIVE_PATH,Environment.DIRECTORY_DOWNLOADS+ File.separator+"MyApp/SubDir")
        }

        val collection = MediaStore.Downloads.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
        val item = contentResolver.insert(collection, values)!!

        contentResolver.openFileDescriptor(item, "w", null).use {
            FileOutputStream(it!!.fileDescriptor).use { outputStream ->
                outputStream.write("test file".toByteArray())
                outputStream.close()
            }
        }

        values.clear()
        values.put(MediaStore.Images.Media.IS_PENDING, 0)
        contentResolver.update(item, values, null, null)

Now my file is save in Downloads/myApp/subDir/file.txt

If so, how can I read this file if I don't know the Uri of this file but know the RELATIVE_PATH used to save it?

1 Answers

It is now possible with the helps of SimpleStorage:

val fileList = MediaStoreCompat.fromRelativePath(this, Environment.DIRECTORY_DOWNLOADS)

val singleFile = MediaStoreCompat.fromRelativePath(this, Environment.DIRECTORY_DOWNLOADS + "/MyApp/SubDir/", "file.txt")
Related