0

I would like to open a simple text file and read this line by line:

I triggered the Open File Dialog like here:

val result = remember { mutableStateOf<Uri?>(null) }
val launcher = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) {
    result.value = it
}

Button(onClick = { launcher.launch(arrayOf("text/plain")) }) {
    Text(text = "Open Document")
}

Loadfile(result.value)

whereas result.value is of type Uri and I try to open file:

@Composable
fun Loadfile(uri: Uri?) {

    Log.d("Loadfile", "Load ${uri.toString()}")

    if(uri==null) {
        Log.e("Loadfile", "File could not load!")    
    } else {
        val file = File(uri.path)
        try {
            BufferedReader(FileReader(file)).use { br ->
                Log.d("Loadfile", "Total Lines: ${br.lines()}")
            }
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }
}

But unfortunately IOException catches a java.io.FileNotFoundException: /document/document:1000014685: open failed: ENOENT (No such file or directory)

The text file is named lola.txt in internal Android Documents folder; I don't know where 1000014685 comes from!? What am I doing wrong?

Abhimanyu
  • 11,351
  • 7
  • 51
  • 121
Ralf Wickum
  • 2,850
  • 9
  • 55
  • 103
  • 1
    Using .path like that will not work, I don't remember exact solution. But it should be about reading uri content as stream – Jemshit Jul 16 '23 at 18:45

0 Answers0