Open In App

Internal Storage in Android with Example

Last Updated : 17 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The aim of this article is to show users how to use internal storage. In this article will be creating an application that can write data to a file and store it in internal storage and read data from the file and display it on the main activity using TextView. Saving and loading data on the internal storage is private for an application that can not be accessed by other applications. When the app is uninstalled the data stored in the internal by that app is removed. To read and write in the Android internal storage we have two methods 

1. OpenFileOutput(): used for creating and saving a file. This method returns a FileOutputStream instance.

Syntax:

OpenFileOutput(String filename,int mode)

Parameters: 

mode: 

  • Context.MODE_PRIVATE: If the file exists then it is overridden else a new file is created. 
  • Context.MODE_APPEND: if the file exists then the data is appended at the end of the file.

Returns: FileOutputStream  object 


2. OpenFileInput(): Used to read data from a file, this returns a FileInputStream instance. 

Syntax:

OpenFileInput( String filename)

Returns: FileInputStream object 

Example

A sample video is given below to get an idea about what we are going to do in this article.

Note: that we are going to implement this project using Java



Step by Step Implementation

Step 1: Create a New Project

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.

Step 2: Working with the activity_main.xml file

The activity_main.xml file has the following widgets 

  1. One EditText for accepting user input
  2. Two Buttons one for reading data and the other for writing
  3. One TextView to display the content of the file

Below is the code for the activity_main.xml file. 

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView2"
        android:layout_width="337dp"
        android:layout_height="28dp"
        android:text="  File Content "
        android:textAlignment="center"
        android:textColor="#000"
        android:textSize="24sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.52" />

    <Button
        android:id="@+id/write_button"
        android:layout_width="wrap_content"
        android:layout_height="48dp"
        android:layout_marginStart="160dp"
        android:layout_marginEnd="159dp"
        android:layout_marginBottom="16dp"
        android:text="Write"
        app:layout_constraintBottom_toTopOf="@+id/read_button"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.904" />

    <Button
        android:id="@+id/read_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="160dp"
        android:layout_marginEnd="158dp"
        android:layout_marginBottom="48dp"
        android:text="Read"
        app:layout_constraintBottom_toTopOf="@+id/textView2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent" />

    <EditText
        android:id="@+id/userInput"
        android:layout_width="319dp"
        android:layout_height="50dp"
        android:layout_marginStart="46dp"
        android:layout_marginTop="91dp"
        android:layout_marginEnd="46dp"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="Name"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/content"
        android:layout_width="332dp"
        android:layout_height="306dp"
        android:layout_marginStart="33dp"
        android:layout_marginTop="21dp"
        android:layout_marginEnd="33dp"
        android:layout_marginBottom="6dp"
        android:text=""
        android:textAlignment="center"
        android:textColor="#000"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.461"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView2"
        app:layout_constraintVertical_bias="0.0" />

</androidx.constraintlayout.widget.ConstraintLayout>

Output UI:

studio64hFXBvEc2QX


Step 3: Working with the MainActivity.java file

Inside the MainActivity.java file we are going to do the following things:

Initialize variables: 

Java
private String filename = "myfile.txt";
read = findViewById(R.id.read_button);
write = findViewById(R.id.write_button);
userInput = findViewById(R.id.userInput);
fileContent = findViewById(R.id.content);


The file will be creating is myfile.txt. this can be found in Device File Explorer > data > data > application_package > files 


file_location


Read and Write methods:

The following method is used to read data from the internal data. 

Java
private void readData() {
        try {
            // Read the content of the file
            FileInputStream fin = openFileInput(filename);
            int a;
            StringBuilder temp = new StringBuilder();
            while ((a = fin.read()) != -1) {
                temp.append((char) a);
            }

            // Set the file content to the TextView
            fileContent.setText(temp.toString());
            fin.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        printMessage("Reading from file " + filename + " completed...");
}


The method used for creating a file and writing data to internal storage. 

Java
private void writeData() {
        try {
            // Write the input text to the file
            FileOutputStream fos = openFileOutput(filename, Context.MODE_PRIVATE);
            String data = userInput.getText().toString();
            fos.write(data.getBytes());
            fos.flush();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        userInput.setText("");  // Clear the input field
        printMessage("Writing to file " + filename + " completed...");
}


Below is the complete code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.

MainActivity.java
package com.example.readwriteinfile;

import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    // declare the variables
    Button read, write;
    EditText userInput;
    TextView fileContent;
    String filename = "myfile.txt";  // Define your filename here

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        // Handle system bars (optional)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        // Initialize the UI components
        read = findViewById(R.id.read_button);
        write = findViewById(R.id.write_button);
        userInput = findViewById(R.id.userInput);
        fileContent = findViewById(R.id.content);

        // Set click listeners
        read.setOnClickListener(this);
        write.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        Button b = (Button) view;

        // Get the button text: either 'read' or 'write' depending on the button pressed
        String b_text = b.getText().toString();

        switch (b_text.toLowerCase()) {
            case "write": {
                writeData();
                break;
            }
            case "read": {
                readData();
                break;
            }
        }
    }

    private void writeData() {
        try {
            // Write the input text to the file
            FileOutputStream fos = openFileOutput(filename, Context.MODE_PRIVATE);
            String data = userInput.getText().toString();
            fos.write(data.getBytes());
            fos.flush();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        userInput.setText("");  // Clear the input field
        printMessage("Writing to file " + filename + " completed...");
    }

    private void readData() {
        try {
            // Read the content of the file
            FileInputStream fin = openFileInput(filename);
            int a;
            StringBuilder temp = new StringBuilder();
            while ((a = fin.read()) != -1) {
                temp.append((char) a);
            }

            // Set the file content to the TextView
            fileContent.setText(temp.toString());
            fin.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        printMessage("Reading from file " + filename + " completed...");
    }

    // A simple method to print messages to the fileContent TextView
    private void printMessage(String message) {
        fileContent.append("\n" + message);
    }
}

Output 



Next Article
Article Tags :
Practice Tags :

Similar Reads