41

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

Kotlinboy
  • 3,725
  • 4
  • 16
  • 27

3 Answers3

87

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.

Kotlinboy
  • 3,725
  • 4
  • 16
  • 27
9

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)
Tatsuya Fujisaki
  • 1,434
  • 15
  • 18
7

When in doubt close the stream yourself!

application.assets.open(file_name).apply {
                json_string = this.readBytes().toString(Charsets.UTF_8)
            }.close()
Juan Mendez
  • 2,658
  • 1
  • 27
  • 23