Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read and write txt files in android in kotlin

Tags:

android

kotlin

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..

like image 426
Khayyam Avatar asked Jul 19 '17 14:07

Khayyam


People also ask

How do I create a text file in Kotlin?

This example demonstrates how to create a text file and insert data to that file on Android using Kotlin. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.

What is the use of read text method in Kotlin?

readText() : returns entire content of file as a single string.


2 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
like image 142
Branson Camp Avatar answered Sep 19 '22 22:09

Branson Camp


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() }
like image 27
TpoM6oH Avatar answered Sep 17 '22 22:09

TpoM6oH