Tutorial

Android Internal Storage Example Tutorial

Published on August 3, 2022
author

Anupam Chugh

Android Internal Storage Example Tutorial

Today we will look into android internal storage. Android offers a few structured ways to store data. These include

In this tutorial we are going to look into the saving and reading data into files using Android Internal Storage.

Android Internal Storage

Android Internal storage is the storage of the private data on the device memory. By default, saving and loading files to the internal storage are private to the application and other applications will not have access to these files. When the user uninstalls the applications the internal stored files associated with the application are also removed. However, note that some users root their Android phones, gaining superuser access. These users will be able to read and write whatever files they wish.

Reading and Writing Text File in Android Internal Storage

Android offers openFileInput and openFileOutput from the Java I/O classes to modify reading and writing streams from and to local files.

  • openFileOutput(): This method is used to create and save a file. Its syntax is given below:

    FileOutputStream fOut = openFileOutput("file name",Context.MODE_PRIVATE);
    

    The method openFileOutput() returns an instance of FileOutputStream. After that we can call write method to write data on the file. Its syntax is given below:

    String str = "test data";
    fOut.write(str.getBytes());
    fOut.close();
    
  • openFileInput(): This method is used to open a file and read it. It returns an instance of FileInputStream. Its syntax is given below:

    FileInputStream fin = openFileInput(file);
    

    After that, we call read method to read one character at a time from the file and then print it. Its syntax is given below:

    int c;
    String temp="";
    while( (c = fin.read()) != -1){
       temp = temp + Character.toString((char)c);
    }
    
    fin.close();
    

    In the above code, string temp contains all the data of the file.

  • Note that these methods do not accept file paths (e.g. path/to/file.txt), they just take simple file names.

Android Internal Storage Project Structure

android internal storage example, android file storage

Android Internal Storage Example Code

The xml layout contains an EditText to write data to the file and a Write Button and Read Button. Note that the onClick methods are defined in the xml file only as shown below: activity_main.xml

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:padding="5dp"
        android:text="Android Read and Write Text from/to a File"
        android:textStyle="bold"
        android:textSize="28sp" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="22dp"
        android:minLines="5"
        android:layout_margin="5dp">

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Write Text into File"
        android:onClick="WriteBtn"
        android:layout_alignTop="@+id/button2"
        android:layout_alignRight="@+id/editText1"
        android:layout_alignEnd="@+id/editText1" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Read Text From file"
        android:onClick="ReadBtn"
        android:layout_centerVertical="true"
        android:layout_alignLeft="@+id/editText1"
        android:layout_alignStart="@+id/editText1" />

</RelativeLayout>

The MainActivity contains the implementation of the reading and writing to files as it was explained above.

package com.journaldev.internalstorage;


import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class MainActivity extends Activity {

    EditText textmsg;
    static final int READ_BLOCK_SIZE = 100;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textmsg=(EditText)findViewById(R.id.editText1);
    }

    // write text to file
    public void WriteBtn(View v) {
        // add-write text into file
        try {
            FileOutputStream fileout=openFileOutput("mytextfile.txt", MODE_PRIVATE);
            OutputStreamWriter outputWriter=new OutputStreamWriter(fileout);
            outputWriter.write(textmsg.getText().toString());
            outputWriter.close();

            //display file saved message
            Toast.makeText(getBaseContext(), "File saved successfully!",
                    Toast.LENGTH_SHORT).show();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // Read text from file
    public void ReadBtn(View v) {
        //reading text from file
        try {
            FileInputStream fileIn=openFileInput("mytextfile.txt");
            InputStreamReader InputRead= new InputStreamReader(fileIn);

            char[] inputBuffer= new char[READ_BLOCK_SIZE];
            String s="";
            int charRead;

            while ((charRead=InputRead.read(inputBuffer))>0) {
                // char to string conversion
                String readstring=String.copyValueOf(inputBuffer,0,charRead);
                s +=readstring;
            }
            InputRead.close();
            textmsg.setText(s);
            

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Here, a toast is displayed when data is successfully written into the internal storage and the data is displayed in the EditText itself on reading the data from the file. The image shown below is the output of the project. The image depicts text being written to the internal storage and on clicking Read it displays back the text in the same EditText. android internal storage, android file storage, Android OpenFileOutput

Where is the file located?

To actually view the file open the Android Device Monitor from Tools->Android->Android Device Monitor. The file is present in the folder data->data->{package name}->files as shown in the images below: android file storage, internal storage, Android OpenFileOutput The file “mytextfile.txt” is found in the package name of the project i.e. com.journaldev.internalstorage as shown below: android file storage, internal storage, Android OpenFileOutput Download the final project for android internal storage example from below link.

Download Android Internal Storage Example Project

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Anupam Chugh

author

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
March 27, 2016

Dear Anupam, thanks for your free example. I’m just starting my first game app using pentacubes and I want to prepare the tasks in files in internal storage. So, the files to write / read works in eclipse and emulator, but not, if I upload the apk on my smartphone. What is the way to realize this ?

- Wilfried

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    February 15, 2017

    Hello! This example helped me a lot more I was left with a doubt, I need to take a photo to the profile of the user (perfil.jpg) and save in Internal Storage If I am saving a profile image of the user and when I start the activity I need to read the profile.jpg file I do not need to check first if it already exists?

    - Robson

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      April 23, 2017

      Thank you

      - Lounnas Abderrahim

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        April 28, 2017

        this code will never work, you have not declared or used the buttons in your class files therefore when you click the button’s nothing will happen.

        - Thabiso

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          May 10, 2017

          hi. thanks when we install this app in mobile, where does the text file locate ? I cannot find it

          - azade

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            June 16, 2017

            Hello! Thanks for the tutorial. I have tried your project on my emulator in Android Studio and on my smartphone but no file is written at all. Do you have any idea about the reason of this behavior? Thanks!

            - Gioppino

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              June 19, 2017

              i can’t find the .txt file in android device emulator

              - venkittu

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                June 19, 2017

                i need how to store in sqllite database and retrieve in .txt file format in android with external storage

                - venkittu

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  July 2, 2018

                  I am not able to find this file in my android phone

                  - Anonymus

                    JournalDev
                    DigitalOcean Employee
                    DigitalOcean Employee badge
                    July 26, 2018

                    Thanks a ton for this. I had been looking high and low on how to save and recall strings.

                    - Bil Bo

                      Try DigitalOcean for free

                      Click below to sign up and get $200 of credit to try our products over 60 days!

                      Sign up

                      Join the Tech Talk
                      Success! Thank you! Please check your email for further details.

                      Please complete your information!

                      Become a contributor for community

                      Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                      DigitalOcean Documentation

                      Full documentation for every DigitalOcean product.

                      Resources for startups and SMBs

                      The Wave has everything you need to know about building a business, from raising funding to marketing your product.

                      Get our newsletter

                      Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

                      New accounts only. By submitting your email you agree to our Privacy Policy

                      The developer cloud

                      Scale up as you grow — whether you're running one virtual machine or ten thousand.

                      Get started for free

                      Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

                      *This promotional offer applies to new accounts only.