Write , read , Delete files in External storage in Android. external storage in Android.


Unlike Internal storage which is private , External storage is a Public storage area which is acessable to anyone.


External storage gets more storage space to use, it takes use of the maximum space given by the device storage.

You can also stored large files which are only related to your app on external storage as private files.
Eg - Pubg maps - they are stored on external storage as private files & get deleted if we delete the game.


External storage consists of 2 types of files : 

1] Public files - we need user permission to read and write data.
2] Private files - dont require user permission.



getExternalFilesDir( ) - use this method to make Private files. Files created using this method get deleted if app is deleted.


getExternalStoragePublicDirectory( ) - use this method to make Public files. Files created using this method do not get deleted if app is deleted.

getExternalStoragePublicDirectory and getExternalStorageDirectory is depreciate in android Q
Android Q has introduced sandboxed approach













Before you use an External Storage , check the following : 

1] If the storage unit is mounted properly (if you are using a ssd card or any other external device for storage)
2] Check if the Storage has WRITE acess.
3] Check if the Storage has READ acess.



-------------------------------------------------------------------------------------------------

useful video : 
https://www.youtube.com/watch?v=qXjonukMxoU&list=PLj76U7gxVixSMap8f38ph5cMjeFB0NSfW&index=10


READING & WRITING TEXT FILES ON EXTERNAL PRIVATE STORAGE


External private files get deleted if app is deleted.

getExternalFilesDir( ) - use this method to make Private files. Files created using this method het deleted if app is deleted.

It takes name of a directory as a parameter & points to it, if dir not found then creates one.

getExternalFilesDir("null") - points to the root directory of External Private storage.


[xml code in the end ]

package com.example.backgroundprogramming;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;


public class MainActivity extends AppCompatActivity {

EditText ed;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

ed = findViewById(R.id.editTextTextPersonName);

//points to the root dir of external private storage.
File file = getExternalFilesDir(null);

// you can also create a custom directory like this.
File file1 = getExternalFilesDir("myCustomDir");

}

public void CreateExternalPrivateFile(View view) {

File file = new File(getExternalFilesDir(null),"myexternalprivatefile.txt");

WriteToFile(file);
}

public void ReadExternalPrivateFile(View view) {

File file = new File(getExternalFilesDir(null),"myexternalprivatefile.txt");

String fromfile = readFromFile(file);

TextView textView = findViewById(R.id.textView2);
textView.setText(fromfile);

}




private void WriteToFile(File file){

FileOutputStream fos = null;

String data = ed.getText().toString();

try {
fos= new FileOutputStream(file);
fos.write(data.getBytes());
Log.d("TAG", "WriteToFile: Data written to file :"
+ file.getName()+ "Path:"+ file.getPath());
}
catch (Exception e){
e.printStackTrace();
}

if (fos != null){
try {
fos.close();
}
catch (Exception e){
e.printStackTrace();
}
}

}

private String readFromFile(File file ){

FileInputStream fis = null;
int read;

StringBuilder sb = new StringBuilder();

try {
fis = new FileInputStream(file);

while ((read = fis.read()) != -1){
sb.append((char) read);
}
}
catch (Exception e){
e.printStackTrace();
}

finally {
if (fis !=null){
try {
fis.close();
}
catch (Exception e){
e.printStackTrace();
}
}
}

return sb.toString();
}



}





---------------------------------------------------------------------------------------------------------

useful video :
 https://www.youtube.com/watch?v=SZPF9KuPIV8&list=PLj76U7gxVixSMap8f38ph5cMjeFB0NSfW&index=11


READING & WRITING TEXT FILES ON EXTERNAL PUBLIC STORAGE


External Public files dont get deleted if the app is deleted.



In order to work with External Public Storage , we'll need to take USER-PERMISSION.

write the permissions required in the manifest file.

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>


------------------------------------


It has 2 important methods (DEPRECATED AFTER ANDROID Q) :



getExternalStoragePublicDirectory("DirectoryName") -

 points to a specific directory inside the root External public  storage directory. example - if you pass "Environment.Directory_Downloads" , it'll point to the downloads folder inside the root External public storage  directory &  reads or writes files from it.


getExternalStorageDirectory() -

points to the root directory for external public storage.



getExternalStoragePublicDirectory and getExternalStorageDirectory is depreciate in android Q or API 29
Android Q has introduced sandboxed approach


--------------------------------


Mainactivity.class
package com.example.backgroundprogramming;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;


public class MainActivity extends AppCompatActivity {

EditText ed;
boolean permissionGranted;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

ed = findViewById(R.id.editTextTextPersonName);

permissionGranted = false;

//points to the Downloads directory inside the Root directory for external public storage.
File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);


}


private void WriteToFile(File file) {

FileOutputStream fos = null;

String data = ed.getText().toString();

try {
fos = new FileOutputStream(file);
fos.write(data.getBytes());
Log.d("TAG", "WriteToFile: Data written to file :"
+ file.getName() + "Path:" + file.getPath());
} catch (Exception e) {
e.printStackTrace();
}

if (fos != null) {
try {
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}

}

private String readFromFile(File file) {

FileInputStream fis = null;
int read;

StringBuilder sb = new StringBuilder();

try {
fis = new FileInputStream(file);

while ((read = fis.read()) != -1) {
sb.append((char) read);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

return sb.toString();
}


public void CreateExternalPublicFile(View view) {

if (!permissionGranted) {
checkPermissions();
}

File file = new File(Environment.getExternalStorageDirectory(), "myexternalpublicfile.txt");

WriteToFile(file);


}

public void ReadExternalPublicFile(View view) {

if (!permissionGranted) {
checkPermissions();
}

File file = new File(Environment.getExternalStorageDirectory(), "myexternalpublicfile.txt");

String fromfile = readFromFile(file);

ed.setText(fromfile);

}

//checks if external storage is available for read & write.
//IMP - If the MEDIA is MOUNTED , then by default it is WRITABLE
public boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
return Environment.MEDIA_MOUNTED.equals(state);
}

//checks if external storage is available for atleast read.
public boolean isExternalStorageReadable() {
String state = Environment.getExternalStorageState();
return (Environment.MEDIA_MOUNTED.equals(state) ||
Environment.MEDIA_MOUNTED_READ_ONLY.equals(state));
}


//requests permissions from users using dialog box.
public boolean checkPermissions() {
if (!isExternalStorageReadable() || !isExternalStorageWritable()) {

Toast.makeText(this, "This app only works with usable external storage", Toast.LENGTH_SHORT).show();
return false;
}

int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1001);
return false;
} else {
return true;
}
}


//handles permissions result
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);

switch (requestCode) {
case 1001:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
permissionGranted = true;
Toast.makeText(this, "External storage permissions granted", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Permissions has been denied, grant permsissions!", Toast.LENGTH_SHORT).show();
}
break;
}
}
}








------------------------------------------------------------------------------------------------------

xml code for the app : 


<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">


<EditText
android:id="@+id/editTextTextPersonName"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="44dp"
android:ems="10"
android:hint="Enter file content"
android:inputType="textPersonName"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="45dp"
android:text="File content appears here..."
android:textSize="25sp"
app:layout_constraintBottom_toTopOf="@+id/button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />

<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="43dp"
android:text="File content appears here..."
android:textSize="25sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/button2" />

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="30dp"
android:layout_marginLeft="30dp"
android:layout_marginTop="216dp"
android:text="Create external public filee "
app:layout_constraintStart_toStartOf="@+id/textView"
app:layout_constraintTop_toTopOf="parent" />

<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="13dp"
android:layout_marginEnd="13dp"
android:layout_marginRight="13dp"
android:text="Read external public file"
app:layout_constraintEnd_toEndOf="@+id/button"
app:layout_constraintTop_toBottomOf="@+id/button" />

<Button
android:id="@+id/button3"
android:onClick="CreateExternalPrivateFile"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="20dp"
android:layout_marginRight="20dp"
android:layout_marginBottom="20dp"
android:text="Create External private file"
app:layout_constraintBottom_toTopOf="@+id/button4"
app:layout_constraintEnd_toEndOf="@+id/textView2" />

<Button
android:id="@+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:layout_marginLeft="5dp"
android:onClick="ReadExternalPrivateFile"
android:layout_marginBottom="42dp"
android:text="Read external private file"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="@+id/button3" />
</androidx.constraintlayout.widget.ConstraintLayout>























Comments

Popular posts from this blog

React Js + React-Redux (part-2)

React Js + CSS Styling + React Router (part-1)

ViteJS (Module Bundlers, Build Tools)