The Wayback Machine - https://web.archive.org/web/20240927131140/https://www.geeksforgeeks.org/internal-storage-in-android-with-example/
Open In App

Internal Storage in Android with Example

Last Updated : 17 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 




Previous Article
Next Article

Similar Reads

How to Get Internal Memory Storage Space in Android Programmatically?
Every device has an internal memory where it can store files and applications. The internal memory of devices can vary anywhere between 4 GB to 512GB. As internal memory gets filled up with a stack of files and applications, the available space decreases. Developers, to save internal memory, design few applications so that they stay compressed when
3 min read
Android Jetpack Compose Internal Storage
Many times in the android application we have to save the data from our android application within the device storage. For storing the data we can store it in shared preferences, internal as well as external storage. In this article, we will take a look at How to save data to Internal storage in Android using Jetpack Compose. Step by Step Implement
6 min read
External Storage in Android with Example
Android gives various options for storing apps data which uses a file system similar to the disk-based system on computer platforms App-Specific storage: Store data files within internal volume directories or external. These data files are meant only for the app's use. It uses internal storage directories to save sensitive information such as a use
9 min read
How to Use Fast Android Networking Library in Android with Example?
In Android, we know multiple networking libraries like Retrofit, Volley. We use these libraries specifically for making networking requests like performing actions on API. But Besides that, there is another library called Fast Networking Library which has a few advantages over other libraries. In this tutorial, we will be specifically focusing on l
4 min read
How to Fetch Audio file From Storage in Android?
Selecting an audio file from the phone's storage is required when the user is uploading or sending an audio file in your application. So this article primarily focuses on getting the audio files as a URI from your phone's storage. Step by Step Implementation Step 1: Create a New Project To create a new project in Android Studio please refer to How
2 min read
Android: How to Upload an image on Firebase storage?
Firebase is a mobile and web application development platform. It provides services that a web application or mobile application might require. Firebase provides secure file uploads and downloads for Firebase application. This article explains how to build an Android application with the ability to select the image from the mobile gallery and uploa
5 min read
Scoped Storage in Android
Working with the file system is an essential element of creating an Android app. Until Android 10, an app could access any file on the device if you granted it storage permission. Most programs, however, do not require access to the whole storage system. They often work on a single file or a small collection of files. This posed a risk to user priv
6 min read
Storage System to Store Data in Android
We employ some form of storage in Android to retain the data permanently (until destroyed) for future reference. Android Storage System is the name given to these storage systems. Internal storage, external storage, shared preferences, database, and shared storage are some of the storage options offered by Android. However, many users are unsure wh
5 min read
Android Jetpack Compose External Storage
Android device provides us with various options to store the data of the application. We can use shared preferences, external storage, and internal storage to store our data. In this article, we will take a look at How to use External storage to store the data within our android application. We will be creating a simple application to save data to
8 min read
Storage Access Framework in Android 13
Storage Access Framework is first introduced in Android 4.4, but has come a long way, and has hugely improved in Android 13. Users can easily browse and open documents, photos, and other files from any of their favorite document storage providers thanks to the SAF. Users may browse files and access recent consistently across apps and providers than
5 min read
How to Compress Image in Android Before Uploading it to Firebase Storage?
Usually, in an app we make users upload images like profile images or others. But there is a chance that the uploaded image is only for display purposes, that too in a short frame. So, these images do not have to be stored in a high-resolution format. Hence even if the user uploads a high-resolution pic, the image must be compressed before storing
4 min read
How to Upload PDF Files in Firebase Storage in Android?
Firebase is a mobile and web application development platform. It provides services that a web application or mobile application might require. Firebase provides secure file uploads and downloads for the Firebase application. This article explains how to build an Android application with the ability to select the pdf from the mobile phone and uploa
3 min read
Android - Upload an Image on Firebase Storage with Kotlin
Firebase Cloud Storage stores files in the Google Cloud Storage bucket and makes them accessible through both Firebase and Google Cloud. It allows us to upload and download files from mobile clients through the Firebase SDKs, and perform server-side processing such as image filtering or video transcoding using the Google Cloud Platform. In this art
6 min read
Java Swing | Internal Frame with examples
JInternalFrame is a part of Java Swing . JInternalFrame is a container that provides many features of a frame which includes displaying title, opening, closing, resizing, support for menu bar, etc. Constructors for JInternalFrame JInternalFrame() : creates a new non- closable, non- resizable, non- iconifiable, non- maximizable JInternalFrame with n
8 min read
Internal Working of ArrayList in Java
ArrayList is a resizable array implementation in Java. ArrayList grows dynamically and ensures that there is always a space to add elements. The backing data structure of ArrayList is an array of Object classes. ArrayList class in Java has 3 constructors. It has its own version of readObject and writeObject methods. Object Array in ArrayList is tra
10 min read
Internal working of Set/HashSet in Java
As we know that a set is a well-defined collection of distinct objects. Each member of a set is called an element of the set. So in other words, we can say that a set will never contain duplicate elements. But how in java Set interface implemented classes like HashSet, LinkedHashSet, TreeSet etc. achieve this uniqueness. In this post, we will discu
3 min read
Internal Working of HashMap in Java
In this article, we will see how the HashMap get and put method works internally. What operations are performed? How the hashing is done. How the value is fetched by key. How the key-value pair is stored.In the previous article, HashMap contains an array of Node and Node can represent a class having the following objects :  int hashK keyV valueNode
8 min read
Android Jetpack - WorkManager with Example
WorkManager is an Android Jetpack library that provides a flexible and efficient way to schedule and manage background tasks in your app. It is a powerful and recommended tool for managing background processing in Android applications. With WorkManager, you can schedule asynchronous, deferred, and periodic tasks that need to run even when the app i
5 min read
Android BottomSheet Example in Kotlin
The Bottom Sheet is seen in many of the applications such as Google Drive, Google Maps and most of the applications used the Bottom Sheet to display the data inside the application. In this article, we will take a look at implementing a Bottom Sheet in the Android app using Kotlin in Android Studio. What is Bottom Sheet? Bottom Sheet is a component
5 min read
Spinner in Android with Example
Android Spinner is a view similar to the dropdown list which is used to select one option from the list of options. It provides an easy way to select one item from the list of items and it shows a dropdown list of all values when we click on it. The default value of the android spinner will be the currently selected value and by using Adapter we ca
4 min read
ImageView in Android with Example
ImageView class is used to display any kind of image resource in the android application either it can be android.graphics.Bitmap or android.graphics.drawable.Drawable (it is a general abstraction for anything that can be drawn in Android). ImageView class or android.widget.ImageView inherits the android.view.View class which is the subclass of Kot
4 min read
PhotoView in Android with Example
In this article, PhotoView is added to android. PhotoView aims to help produce an easily usable implementation of a zooming Android ImageView using multi-touch and double-tap. Besides that, it has many more features like it notifying the application when the user taps on the photo or when the displayed matrix gets changed. It provides smooth scroll
2 min read
NestedScrollView in Android with Example
NestedScrollView is just like ScrollView, but it supports acting as both a nested scrolling parent and child on both new and old versions of Android. It is enabled by default. NestedScrollView is used when there is a need for a scrolling view inside another scrolling view. You have seen this in many apps for example when we open a pdf file and when
5 min read
Bundle in Android with Example
It is known that Intents are used in Android to pass to the data from one activity to another. But there is one another way, that can be used to pass the data from one activity to another in a better way and less code space ie by using Bundles in Android. Android Bundles are generally used for passing data from one activity to another. Basically he
6 min read
Activity State Changes In Android with Example
Prerequisites: Activity lifecycle in android As it is known that every Android app has at least one activity associated with it. When the application begins to execute and runs, there are various state changes that activity goes through. Different events some user-triggered and some system triggered can cause an activity to do the transition from o
6 min read
Floating Action Button (FAB) in Android with Example
The floating action button is a bit different button from the ordinary buttons. Floating action buttons are implemented in the app's UI for primary actions (promoted actions) for the users and the actions under the floating action button are prioritized by the developer. For example the actions like adding an item to the existing list. So in this a
8 min read
Theming Floating Action Buttons in Android with Example
Prerequisite: Floating Action Button (FAB) in Android with ExampleExtended Floating Action Button in Android with Example Android application developers want to seek the attention of the users by customizing and theming the android application widgets and keep more traffic of customers only by the design of the application. In this article, it has
12 min read
ArrayAdapter in Android with Example
The Adapter acts as a bridge between the UI Component and the Data Source. It converts data from the data sources into view items that can be displayed into the UI Component. Data Source can be Arrays, HashMap, Database, etc. and UI Components can be ListView, GridView, Spinner, etc. ArrayAdapter is the most commonly used adapter in android. When y
3 min read
SlidingDrawer in Android with Example
SlidingDrawer is a common requirement in android mobiles to view the content whenever needed by sliding horizontally as well as vertically. In this article, let us check out Sliding Drawer which is used to hide the content out from the screen and allows the user to drag a handle to bring the content on the screen whenever needed in a very user-frie
9 min read
MVC (Model View Controller) Architecture Pattern in Android with Example
Developing an android application by applying a software architecture pattern is always preferred by the developers. An architecture pattern gives modularity to the project files and assures that all the codes get covered in Unit testing. It makes the task easy for developers to maintain the software and to expand the features of the application in
8 min read
Article Tags :
Practice Tags :