Save Data in Android Internal Storage

Internal storage is used to save and retrieve the application’s private data. Other applications don’t have access to this data. Files will be removed when the user uninstalls the application. Files are stored in the app data folder:

  • /data/data/<PACKAGE_NAME>/files/<FILE_NAME>

To save data in a file, we need to open it using the openFileOutput() method with the name of the file. This method returns an instance of FileOutputStream. After that we can write data to the file.

The method openFileInput() can be used to open file for reading. It returns an instance of FileInputStream. After that we can read data from the file.

package com.example.app

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log

class MainActivity : AppCompatActivity()
{
    private val fileName: String = "my_file.txt"

    override fun onCreate(savedInstanceState: Bundle?)
    {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        write("Hello world")
        val message = read()

        Log.d("MY_APP", message!!)
    }

    private fun write(message: String)
    {
        val fileOut = openFileOutput(fileName, MODE_PRIVATE)

        fileOut.write(message.toByteArray())
        fileOut.close()
    }

    private fun read(): String?
    {
        val fileIn = openFileInput(fileName)

        val message = fileIn.readBytes().toString(Charsets.UTF_8)
        fileIn.close()

        return message
    }
}

Leave a Comment

Your email address will not be published. Required fields are marked *