Android Tutorial: Using Internal Storage for Data Management

In this post, we look at Android’s internal storage. Android offers several structured ways to store data, including:

  • Shared Preferences
  • Internal Storage
  • External Storage
  • SQLite Storage
  • Network Connection Storage (Cloud)

In this tutorial, we focus on how to store and read data in files using Android’s internal storage.

Android Internal Storage

Android’s internal storage is the space for private data on the device’s memory. By default, files stored and loaded in internal storage are only visible to the application, and other applications do not have access to them. If the user uninstalls the application, the associated files are also removed. However, note that some users root their Android phones, gaining superuser access, which allows them to read and write all files.

Reading and Writing Text Files in Internal Storage

Android provides the openFileInput and openFileOutput methods from the Java I/O classes to manage read and write streams to local files.

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

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

    This method returns an instance of FileOutputStream. The write method can then be called to write data to the file:

    
    
    String str = "Test data";
    fOut.write(str.getBytes());
    fOut.close();

  • openFileInput(): This method is used to open and read a file. It returns an instance of FileInputStream. The syntax is:

    FileInputStream fin = openFileInput("filename");

    The read method can then be called to read the file character by character:

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

    In this code, the temp variable contains all the data from the file.

Note: These methods do not accept file paths (e.g., path/to/file.txt), only simple filenames.

Example of an Android Project Using Internal Storage

The XML layout file (activity_main.xml) contains an EditText field for writing data to the file, as well as a write and read button. The layout is defined as:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    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: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_below="@+id/textView1"
        android:minLines="5">
        <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" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Read Text From file"
        android:onClick="ReadBtn" />
</RelativeLayout>

The MainActivity contains the implementation of the read and write operations:

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);
    }

    public void WriteBtn(View v) {
        try {
            FileOutputStream fileout = openFileOutput("mytextfile.txt", MODE_PRIVATE);
            OutputStreamWriter outputWriter = new OutputStreamWriter(fileout);
            outputWriter.write(textmsg.getText().toString());
            outputWriter.close();
            Toast.makeText(getBaseContext(), "File saved successfully!", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void ReadBtn(View v) {
        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) {
                String readstring = String.copyValueOf(inputBuffer, 0, charRead);
                s += readstring;
            }
            InputRead.close();
            textmsg.setText(s);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

A toast message is displayed when the data is successfully saved in internal storage. When reading, the data is displayed in the EditText field.

To view the file, open the Android Device Monitor via Tools -> Android -> Android Device Monitor. The file is located in the data -> data -> {package name} -> files folder.

Create a Free Account

Register now and get access to our Cloud Services.

Posts you might be interested in: