Reading and writing files in Android using Kotlin Android 14.10.2019

Using internal storage

The internal storage, by default, is private to your app. The system creates an internal storage directory for each app and names it with the app’s package name. When you uninstall the app, files saved in the internal storage directory are deleted. If you need files to persist — even after the app is uninstalled — use external storage.

Writng to internal storage.

val fileName = "test.txt"
val fileBody = "test"

context.openFileOutput(fileName, Context.MODE_PRIVATE).use { output ->
    output.write(fileBody.toByteArray())
}

Reading from internal storage.

context.openFileInput(fileName).use { stream ->
    val text = stream.bufferedReader().use {
        it.readText()
    }
    Log.d("TAG", "LOADED: $text")
}

Using external storage

External storage is not guaranteed to be accessible at all times; sometimes it exists on a physically removable SD card. Before attempting to access a file in external storage, you must check for the availability of the external storage directories, as well as the files. You can also store files in a location on the external storage system, where they will be deleted by the system when the user uninstalls the app.

To use external storage, you must first add the correct permission to the manifest. If you wish to only read external files, use the READ_EXTERNAL_FILE permission.

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

If you want to both read and write, use the WRITE_EXTERNAL_STORAGE permission.

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

Writng the notes to external storage. The isExternalStorageWritable function determines if the external storage is mounted and ready for read/write operations, whereas isExternalStorageReadable determines only if the storage is ready for reading.

fun isExternalStorageWritable(): Boolean {
    return Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED 
}

fun isExternalStorageReadable(): Boolean { 
    return Environment.getExternalStorageState() in
        setOf(Environment.MEDIA_MOUNTED, Environment.MEDIA_MOUNTED_READ_ONLY)
}

if (isExternalStorageWritable()) {
    FileOutputStream(fileName).use { output ->
        output.write(fileBody.toByteArray())
    }
}

Reading from external storage

if (isExternalStorageReadable()) {
    FileInputStream(fileName).use { stream ->
        val text = stream.bufferedReader().use {
            it.readText()
        }
        Log.d("TAG", "LOADED: $text")
    }
}