Tutorials  /  JavaScript

Android Tutorial: Using Internal Storage for Data Management

Ccentron Redaktion · September 2024 ·3 min read ·JavaScript, Tutorial

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.

VM

Matching infrastructure at centron

Node applications need somewhere to run: ccloud³ VMs with full root access from €3.12 per month – or as a managed server if you would rather not run it yourself. Rent a cloud server →

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:
    Code
    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:

    Code
    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:
    Code
    FileInputStream fin = openFileInput("filename");

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

    Code
    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:

Code
<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:

Go
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.

Jetzt 200 € Guthaben sichern

Testen Sie Ihr Setup auf ccloud³

Registrieren Sie sich in der ccloud³ und erhalten Sie 200 € Startguthaben für Ihr Projekt – z. B. für eine PostgreSQL-VM mit automatischen Backups.

centron Redaktion Technische Redaktion

Das Redaktionsteam von centron schreibt Anleitungen aus dem Betriebsalltag: getestet auf unserer eigenen Plattform, betrieben im Rechenzentrum in Hallstadt bei Bamberg.

Kategorie JavaScript
Teilen
Noch offene Fragen?

Our team will help you with your specific setup - in German or English, by people who run the platform themselves.

War dieses Tutorial hilfreich?

Your answer is stored anonymously and helps us improve our tutorials.

Kommentare

No comments yet - be the first to ask a question about this tutorial.

Sign in to comment

Comments are open to centron customers. Sign in to your account to ask a question about this tutorial.

Weiterlesen

Das könnte Sie auch interessieren

Jetzt kostenlos anfangen

Melden Sie sich an und erhalten Sie in den ersten 60 Tagen ein Guthaben von 200 € bei centron.

Dieses Werbeangebot gilt nur für neue Konten. Angebot ausschließlich für Gewerbetreibende.

Jetzt loslegen Sales kontaktieren