Every android application needs a way to store data, Android offers a few ways to store data, which Includes:
- Internal Storage
- External Storage
- SharedPreferences
- SQLite Database
- Cloud Storage (via Network)
In this tutorial we will use Android internal storage to store and read data into files.
Android Internal Storage
Android Internal storage is Device internal memory and that can be used to store data or files. The File or data stored on internal storage is private by default, and can only be accessed by the same application and can not be accessed by other apps.
- To Perform Write Operation on Internal Storage openFileOutput() method is used
- To Perform Read Operation on Internal Storage openFileInput() method is used
Write file in Internal Storage
To Perform write operation on internal Storage we will be using openFileOutput() method.
This method is used to create and save file.
Syntax:
openFileOutput(String filename, int mode)
Here, the first parameter is the filename and the second parameter is MODE. In Mode parameter you can pass Context.MODE_PRIVATE, this will create a new file in private mode and if file exists then it will override. You can also pass Context.MODE_APPEND, this will create a new file in append mode and If file already exists then the data is appended at the end of the file.
FileOutputStream fileOutputStream = openFileOutput("filename", Context.MODE_PRIVATE);
openFileOutput() method returns the instance of FileOutputStream. FileOutputStream is an outputstream for writing data streams of raw bytes to file and we will use the write method of FileOutputStream to write data of bytes on file.
private void writeData(String fileName, String fileData) {
try {
FileOutputStream fileOutputStream = openFileOutput(fileName, MODE_PRIVATE);
fileOutputStream.write(fileData.getBytes());
fileOutputStream.flush();
fileOutputStream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
Read file from Internal Storage
To Perform read operation on internal Storage we will be using openFileInput() method.
This method is used to read files from Internal Storage and this method is part of java.io package in java.
Syntax:
openFileInput(String filename)
Here, the only parameter passed is filename
FileInputStream fileInputStream = openFileInput("filename");
This method returns the instance of FileInputStream. FileInputStream class in Java is useful for reading data from a file in the form of a sequence of bytes.
private String readData(String fileName) {
try {
FileInputStream fileInputStream = openFileInput(fileName);
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
String text = null;
while ((text = bufferedReader.readLine()) != null) {
stringBuilder.append(text);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
Here, In readData() method InputStreamReader is used to convert the sequence of bytes into the character streams and BufferedReader class’s readLine() method is used to read data from file.
Step by Step Code Implementation
Here, we have created a app which will write and read data from the file (Internal Storage).
File : activity_main.xml
The activity_main.xml layout file contains two EditText, one for the filename and one to write data and two buttons to read data from the file and to write data on the file.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity"
android:gravity="center"
android:padding="16dp"
>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/file_name_et"
android:inputType="text"
android:hint="Enter file name"
android:autofillHints="no"
/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/file_data_et"
android:inputType="text"
android:hint="Enter file data"
android:autofillHints="no"
android:layout_marginTop="20dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Data"
android:textSize="20sp"
android:layout_marginTop="10dp"
android:visibility="gone"
android:id="@+id/data_tv"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
>
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Save data"
android:layout_weight="1"
android:id="@+id/btn_save_file"
/>
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Read Data"
android:layout_weight="1"
android:id="@+id/btn_read_file"
android:layout_marginStart="20dp"
/>
</LinearLayout>
</LinearLayout>
The MainActivity contains the implementation of the reading and writing to files from the internal – storage.
MainActivity: Kotlin/Java File
package com.vairagicodes.internalstorageexample
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 java.io.BufferedReader
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStreamReader
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val saveButton: Button = findViewById(R.id.btn_save_file)
val readButton: Button = findViewById(R.id.btn_read_file)
val fileNameEt: EditText = findViewById(R.id.file_name_et)
val fileDataEt: EditText = findViewById(R.id.file_data_et)
val dataTextView: TextView = findViewById(R.id.data_tv)
saveButton.setOnClickListener {
val name = fileNameEt.text.toString()
val data = fileDataEt.text.toString()
writeData(name, data)
}
readButton.setOnClickListener {
val name = fileNameEt.text.toString()
val data = readData(name)
dataTextView.visibility = View.VISIBLE
dataTextView.text = data
}
}
private fun writeData(fileName: String, fileData: String) {
try {
val fileOutputStream: FileOutputStream = openFileOutput(fileName,
MODE_PRIVATE)
fileOutputStream.write(fileData.toByteArray())
fileOutputStream.flush()
fileOutputStream.close()
} catch (e: IOException) {
throw RuntimeException(e)
}
}
private fun readData(fileName: String): String {
return try {
val fileInputStream: FileInputStream = openFileInput(fileName)
val inputStreamReader = InputStreamReader(fileInputStream)
val bufferedReader = BufferedReader(inputStreamReader)
val stringBuilder = StringBuilder()
var text: String?
while (bufferedReader.readLine().also { text = it } != null) {
stringBuilder.append(text)
}
stringBuilder.toString()
} catch (e: IOException) {
throw RuntimeException(e)
}
}
}
package com.vairagicodes.internalstorageexample;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button saveButton = findViewById(R.id.btn_save_file);
Button readButton = findViewById(R.id.btn_read_file);
EditText fileNameEt = findViewById(R.id.file_name_et);
EditText fileDataEt = findViewById(R.id.file_data_et);
TextView dataTextView = findViewById(R.id.data_tv);
saveButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String name = fileNameEt.getText().toString();
String data = fileDataEt.getText().toString();
writeData(name,data);
}
});
readButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String name = fileNameEt.getText().toString();
String data = readData(name);
dataTextView.setVisibility(View.VISIBLE);
dataTextView.setText(data);
}
});
}
private void writeData(String fileName, String fileData) {
try {
FileOutputStream fileOutputStream = openFileOutput(fileName,
MODE_PRIVATE);
fileOutputStream.write(fileData.getBytes());
fileOutputStream.flush();
fileOutputStream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private String readData(String fileName) {
try {
FileInputStream fileInputStream = openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream);
BufferedReader bufferedReader =
new BufferedReader(inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
String text = null;
while ((text = bufferedReader.readLine()) != null) {
stringBuilder.append(text);
}
return stringBuilder.toString();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
Output:
Download the final project for android internal storage example from below link :