How to read and write txt files in android in kotlin

后端 未结 5 1120
小鲜肉
小鲜肉 2021-02-05 22:17

I\'m still pretty much a beginner in kotlin and android studio. I can access most of the android widgets but I cannot access files and so far I managed to come across only the f

5条回答
  •  时光取名叫无心
    2021-02-05 23:14

    Kotlin has made file reading/writing quite simple.

    For reading/writing to internal storage:

    context.openFileOutput(filename, Context.MODE_PRIVATE).use {
        it.write(message.toByteArray())
    }
    .
    .
    .
    val file = File(context.filesDir, "myfile.txt")
    val contents = file.readText() // Read file
    

    For reading/writing to external storage:

    val file = File(Environment.getExternalStorageDirectory()+"/path/to/myfile.txt")
    file.writeText("This will be written to the file!")
    .
    .
    .
    val contents = file.readText() // Read file
    

提交回复
热议问题