Home > Software engineering >  Trying to read a text file using application.assets - gives "Unresolved reference"
Trying to read a text file using application.assets - gives "Unresolved reference"

Time:04-05

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.

CodePudding user response:

The context is not needed. FileInputStream() receives a string path to find the document, should work as the following:

val asset = FileInputStream(stringAssetPath).bufferedReader()
            .use { it.readText() }

CodePudding user response:

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.

  • Related