How to read and write txt files in android in kotlin

Viewed 62570

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 following code which does not work. The app crashes...

var recordsFile = File("/LET/Records.txt")
recordsFile.appendText("record goes here")

It will be much appreciated if I can also know how to create the file at a specific location. Like at root directory or internal storage or in a file in the internal storage. Thanks..

5 Answers

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

In 5 lines: create file to internal directory if not exists, write to file, read file

val file = File(ctx.filesDir, FILE_NAME)
file.createNewFile()
file.appendText("record goes here")
val readResult = FileInputStream(file).bufferedReader().use { it.readText() }
println("readResult=$readResult")
fun loadWords(context: Context): ArrayList<String> {
        
    val Word = ArrayList<String>()
        var line: String
        var word = ""
        var weight = 0
        try {
            val reader: BufferedReader
            val file = context.assets.open("spam_keywords.txt")
            reader = BufferedReader(InputStreamReader(file))
            while ((reader.readLine()) != null) {
                line = reader.readLine()
                val st = StringTokenizer(line)
                while (st.hasMoreElements()) {
                    word = st.nextElement().toString()
                }
                Word.add(word)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        println(Word)
        return Word 
    }
Related