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..
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.
readText() : returns entire content of file as a single string.
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() }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With