Lorenzo Battilocchi
Lorenzo Battilocchi

Reputation: 1168

Reading file from android Internal storage

I have placed a file in my Tablet\Tablet\Android\data\my.app.package\files\data called test.txt with a few lines of text. This is reported by Windows.

Kotlin is throwing an Exception (FileNotFound) and I have also tried specifying what I believe is the real path of the file, but cannot seem to get it using the following path:

"/0/Android/data/my.app.package/files/data/test.txt" (my app's data directory). This directory definitely exists as I can see it in device file managr.

This file contains 2 lines of text, which I am trying to read in to run specific tasks based on their values. I've tried with a BufferedReader, but I'm getting FileNotFound Exception...

This is my code:

fun readFile() {
    val yourFilePath = "/0/Android/data/my.app.package/files/data/test.txt"
    val yourFile = File(yourFilePath)

    print(yourFile.name)
    val file = File(yourFilePath)
    file.bufferedReader().forEachLine {
        println("value = $it")
    }

}

Any help is highly appreciated. Thankyou!

Upvotes: 3

Views: 5265

Answers (2)

Leonid Ivankin
Leonid Ivankin

Reputation: 667

context.openFileInput(fileName).use { stream ->
   stream.bufferedReader().use { it.readText() }
}

Upvotes: 0

Arrowsome
Arrowsome

Reputation: 2859

  1. filesDir for pointing to the internal storage files directory
  2. use blocks are good when you want to close stream automatically.
  3. try-catch block to handle any IO exceptions, e.g. FileNotFoundException.
try {
    val file = File(filesDir, "test.txt")
    if (file.exists()) {
        file.bufferedReader().useLines {
            ...
        }
    }
} catch (e: IOException) {
    ...
}

Great article for a more in-depth look: Medium

Make sure your file exists by looking at your internal storage by:

AndroidStudio -> View -> Tools Windows -> Android Device Explorer

Upvotes: 3

Related Questions