0
0
Android Kotlinmobile~5 mins

File access and storage in Android Kotlin

Choose your learning style9 modes available
Introduction

Files let your app save and read information on the device. This helps keep data even when the app is closed.

Saving user notes or documents locally on the phone.
Storing app settings or preferences that need to persist.
Caching images or data to load faster next time.
Logging app events for debugging or support.
Reading configuration files bundled with the app.
Syntax
Android Kotlin
val fileOutput = openFileOutput("filename.txt", Context.MODE_PRIVATE)
fileOutput.write("Hello World".toByteArray())
fileOutput.close()

val fileInput = openFileInput("filename.txt")
val content = fileInput.bufferedReader().use { it.readText() }
fileInput.close()

openFileOutput creates or opens a file for writing inside your app's private storage.

openFileInput opens a file for reading from your app's private storage.

Examples
Write text to a private file safely using use to auto-close the stream.
Android Kotlin
openFileOutput("data.txt", Context.MODE_PRIVATE).use {
  it.write("Sample text".toByteArray())
}
Read all text from a private file using a buffered reader.
Android Kotlin
val text = openFileInput("data.txt").bufferedReader().use {
  it.readText()
}
Use File class with filesDir to write and read text files.
Android Kotlin
val file = File(filesDir, "myfile.txt")
file.writeText("Hello")
val content = file.readText()
Sample App

This app writes a message to a private file and then reads it back to show on screen.

Android Kotlin
import android.app.Activity
import android.content.Context
import android.os.Bundle
import android.widget.TextView
import java.io.File

class MainActivity : Activity() {
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    val filename = "example.txt"
    val fileContents = "Welcome to file storage!"

    openFileOutput(filename, Context.MODE_PRIVATE).use {
      it.write(fileContents.toByteArray())
    }

    val readText = openFileInput(filename).bufferedReader().use {
      it.readText()
    }

    val textView = TextView(this).apply {
      text = readText
      textSize = 24f
    }

    setContentView(textView)
  }
}
OutputSuccess
Important Notes

Files saved with MODE_PRIVATE are only accessible by your app.

Always close streams or use use to avoid leaks.

For large files or complex data, consider using databases or shared preferences instead.

Summary

File access lets apps save and read data on the device.

Use openFileOutput and openFileInput for private app files.

Always handle files carefully to avoid crashes or data loss.