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

Viewed 28478

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

3 Answers

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.

When in doubt close the stream yourself!

application.assets.open(file_name).apply {
                json_string = this.readBytes().toString(Charsets.UTF_8)
            }.close()

You don’t need Application to read a text file in the assets folder.

fun readAsset(context: Context, fileName: String): String =
    context
        .assets
        .open(fileName)
        .bufferedReader()
        .use(BufferedReader::readText)
Related