Reputation: 1168
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
Reputation: 667
context.openFileInput(fileName).use { stream ->
stream.bufferedReader().use { it.readText() }
}
Upvotes: 0
Reputation: 2859
filesDir
for pointing to the internal storage files directoryuse
blocks are good when you want to close stream automatically.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