How to read and write txt files in android in kotlin

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

You need to use internal or external storage directory for your file.

Internal:

val path = context.getFilesDir()

External:

val path = context.getExternalFilesDir(null)

If you want to use external storage you'll need to add a permission to the manifest:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Create your directory:

val letDirectory = File(path, "LET")
letDirectory.mkdirs()

Then create your file:

val file = File(letDirectory, "Records.txt")

Then you can write to it:

FileOutputStream(file).use {
    it.write("record goes here".getBytes())
}

or just

file.appendText("record goes here")

And read:

val inputAsString = FileInputStream(file).bufferedReader().use { it.readText() }

Tags:

Android

Kotlin