Read a Text asset(text file from assets folder) as a String in Kotlin (Android)

Kotlinboy picture Kotlinboy · Nov 9, 2017 · Viewed 20.8k times · Source

I need to read a text file stored at src/main/assets/ i.e; in the assets folder and get it as a string.

Is there a simple way to do it.

Java copy, paste, convert functions are giving trouble, so I'd rather use a kotlin way.

I need a kotlin way to do this

Answer

Kotlinboy picture Kotlinboy · Nov 9, 2017

I found this in a youtube video. Here is the link https://www.youtube.com/watch?v=o5pDghyRHmI

val file_name = "qjsonfile.json"
val json_string = application.assets.open(file_name).bufferedReader().use{
            it.readText()
        }

Saves the JSON or text to the string json_string.