External Storage in Android
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 External storage in android to store and read data into files.
External storage in Android (Such as SD Card) is Also used for storing data. We just need to check if the External storage is available or not, The method getExternalStorageState() is used to check if the External Storage is available or not. If it’s available then we can also read and write on External storage. To Read and Write on external Storage FileInputStream and FileOutputStream classes are used.
Initial Steps For Read and Write on External Storage
- Need a permission to read and write data on External Storage
- Also Need to check if the External Storage is Available or not
- First We need a permission to read and write on external storage, for that we will declare permission in AndroidManifest.xml File
- External storage in android may be available, so we need to check if the external storage is available or not and is not read only
private static boolean isExternalStorageReadOnly() {
String extStorageState = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) {
return true;
}
return false;
}
private static boolean isExternalStorageAvailable() {
String extStorageState = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(extStorageState)) {
return true;
}
return false;
}
getExternalStorageState() is static method of Environment class which is used to check if the external storage is available or not and If it’s not read only
Write file on External Storage in Android
In Android, To write data on External Storage We will be using 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.
Code:
private void writeData(File file, String fileData) {
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(fileData.getBytes());
fileOutputStream.flush();
fileOutputStream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
Read file from External Storage in Android
In Android, To Read data from External Storage We will be using FileInputStream. FileInputStream class in Java is useful for reading data from a file in the form of a sequence of bytes
Code:
private String readData(File file) {
try {
FileInputStream fileInputStream = new FileInputStream(file);
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);
}
}
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 (External Storage in Android).
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:gravity="center"
android:orientation="vertical"
android:padding="16dp"
tools:context=".MainActivity">
<EditText
android:id="@+id/file_name_et"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:autofillHints="no"
android:hint="Enter file name"
android:inputType="text" />
<EditText
android:id="@+id/file_data_et"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:autofillHints="no"
android:hint="Enter file data"
android:inputType="text" />
<TextView
android:id="@+id/data_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="Data"
android:textSize="20sp"
android:visibility="gone" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp">
<Button
android:id="@+id/btn_save_file"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Save data" />
<Button
android:id="@+id/btn_read_file"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:layout_weight="1"
android:text="Read Data"
/>
</LinearLayout>
</LinearLayout>
The MainActivity contains the implementation of the reading and writing to files from the External – Storage.
MainActivity: Kotlin/Java File
package com.vairagicodes.externalstorageexample
import android.os.Bundle
import android.os.Environment
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import java.io.BufferedReader
import java.io.File
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 {
if (isExternalStorageReadOnly() || !isExternalStorageAvailable()) {
Toast.makeText(this, "Storage is not available", Toast.LENGTH_SHORT).show()
} else {
val file = File(getExternalFilesDir("VairagiCodes"), fileNameEt.text.toString())
writeData(file, fileDataEt.text.toString())
}
}
readButton.setOnClickListener {
if (isExternalStorageReadOnly() || !isExternalStorageAvailable()) {
Toast.makeText(this, "Storage is not available", Toast.LENGTH_SHORT).show()
} else {
val file = File(getExternalFilesDir("VairagiCodes"), fileNameEt.text.toString())
val data = readData(file)
dataTextView.visibility = View.VISIBLE
dataTextView.text = data
}
}
}
private fun isExternalStorageReadOnly(): Boolean {
val extStorageState = Environment.getExternalStorageState()
return Environment.MEDIA_MOUNTED_READ_ONLY == extStorageState
}
private fun isExternalStorageAvailable(): Boolean {
val extStorageState = Environment.getExternalStorageState()
return Environment.MEDIA_MOUNTED == extStorageState
}
private fun writeData(file: File, fileData: String) {
var fileOutputStream: FileOutputStream? = null
try {
fileOutputStream = FileOutputStream(file)
fileOutputStream.write(fileData.toByteArray())
fileOutputStream.flush()
} catch (e: IOException) {
throw RuntimeException(e)
} finally {
fileOutputStream?.close()
}
}
private fun readData(file: File): String {
return try {
val fileInputStream = FileInputStream(file)
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.externalstorageexample;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.io.BufferedReader;
import java.io.File;
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 data_tv = findViewById(R.id.data_tv);
saveButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (isExternalStorageReadOnly() || !isExternalStorageAvailable()) {
Toast.makeText(MainActivity.this, "Storage is not available", Toast.LENGTH_SHORT).show();
} else {
File file = new File(getExternalFilesDir("VairagiCodes"), fileNameEt.getText().toString());
writeData(file, fileDataEt.getText().toString());
}
}
});
readButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (isExternalStorageReadOnly() || !isExternalStorageAvailable()) {
Toast.makeText(MainActivity.this, "Storage is not available", Toast.LENGTH_SHORT).show();
} else {
File file = new File(getExternalFilesDir("VairagiCodes"), fileNameEt.getText().toString());
String data = readData(file);
data_tv.setVisibility(View.VISIBLE);
data_tv.setText(data);
}
}
});
}
private static boolean isExternalStorageReadOnly() {
String extStorageState = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) {
return true;
}
return false;
}
private static boolean isExternalStorageAvailable() {
String extStorageState = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(extStorageState)) {
return true;
}
return false;
}
private void writeData(File file, String fileData) {
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(fileData.getBytes());
fileOutputStream.flush();
fileOutputStream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private String readData(File file) {
try {
FileInputStream fileInputStream = new FileInputStream(file);
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 External storage in android example from below link :