I’m new to Kotlin and trying to read a text file in my app. I’ve been trying all the suggestions I can find without success. I’ve put a text file in assets and I’ve tried
val resultLines = application.assets.open("myLines.txt").readLines()
but application is shown in red with an "Unresolved reference" error. I’ve tried
val resultLines = requireContext().assets?.open("myLines.txt").toString()
but it crashes. Another suggestion was
val fileText: String = applicationContext.assets.open( fileName: "textfile.txt").bufferedReader() .use { it.readText () }
but applicationContext was an Unresolved reference.
All I want to do is read a text file with a few lines of text into a List.
2
Answers
Based on CoolMind's comment above, I found tutorialspoint.com/how-to-read-files-from-assets-on-android-using-kotlin which was what I wanted. That contains code for a new Project which I set up and it works. (I had to modify it slightly for it to compile in a Fragment rather than Main.)
My original question about "Unresolved reference" has not got an answer that worked for me but it no longer occurs now that I have changed the code considerably, using the method in the website mentioned above.
The context is not needed. FileInputStream() receives a string path to find the document, should work as the following: