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..
You need to use internal or external storage directory for your file.
Internal:
External:
If you want to use external storage you'll need to add a permission to the manifest:
Create your directory:
Then create your file:
Then you can write to it:
or just
And read:
In 5 lines: create file to internal directory if not exists, write to file, read file
I just want to add on to TpoM6oH's answer. When working with Files, you may be not guaranteed with 100% success on the file operations you intend. So, it is a better practice to try and catch for exceptions like filenotfoundexception etc. and take a due care about the flow of program control.
To create a file at the external storage in Android, you can get the location using
and check if the location exists. If it does not, create one and continue creating and writing your file using Kotlin
Hope this helps.
Kotlin has made file reading/writing quite simple.
For reading/writing to internal storage:
For reading/writing to external storage: