Write , read , Delete files in Internal storage in Android. Internal storage in Android.
useful video :
https://youtu.be/iOthBqwHLRg
All the Code is Pure Java & comes from .io package
Internal Storage is not visible to the user in the file manager , unless the device is rooted.
---------------------------------------------------------------------------------------------
As you know files on the Internal storage get deleted with the App , also keep in mind if you do "CLEAR DATA" , that will erase the internal files of that App.
In the internal Storage , you can store Text files & Binary files only .
Text files are stored in the form of Bytes.
If you want to store media files , store them in Binary format.
Use Output Stream when you want to write into a file , and use InputStream when you want to read a file.
--------------------------------------------------------------------------------
useful video :
https://www.youtube.com/watch?v=YyVxkZVr-Cs&list=PLj76U7gxVixSMap8f38ph5cMjeFB0NSfW&index=3
In the actual phone , you cannot acess the Internal storage files other than the app itself.
Yet you can see the Internal files in the Android studio though using the Device File Manager.
All the Internal storage files are stored in One specific directry.
To get the absolute path of Internal files Directry use the method below.
String path = getFilesDir().getAbsolutePath();-------------------------------------------------------------------------------------------------------
CREATE & WRITE A TEXT FILE:
You can find the file at the absolute path directory and open it.
In actual app , this file wont be acessable to the user.
[xml code in the end of blog]
package com.example.internalstorageapp;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
TextView textView;
FileOutputStream fos;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
//There is only one directory for internal storage for a app.
// this gets the absolute path of Internal storage directory.
String path = getFilesDir().getAbsolutePath();
textView.setText(path);
}
//User click the Create File button
public void CreateFile(View view) {
EditText ed = findViewById(R.id.editTextTextPersonName);
String data = ed.getText().toString();
fos = null;
try {
// get a outputstream
fos =openFileOutput("mydemofile",MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
// write the file
fos.write(data.getBytes());
textView.setText("File Written");
} catch (IOException e) {
e.printStackTrace();
}
finally {
if (fos != null){
try {
// close the stream
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
-------------------------------------------------------------------------------------------------------
READ TEXT FILES :
Since Text files are stored in the form of BTYES, when we retrieve them we get them in byte format (i.e in the form of 1 & 0).
We can convert the bytes to character , once they are converted to character we can then append them in the stringbuilder and get the entire text file.
We convert each integer byte to character and then append it to the stringbuilder until it builds the entire string file.
package com.example.internalstorageapp;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class MainActivity extends AppCompatActivity {
TextView textView;
FileOutputStream fos;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
//There is only one directory for internal storage for a app.
// this gets the absolute path of Internal storage directory.
String path = getFilesDir().getAbsolutePath();
textView.setText(path);
}
//User click the Create File button
public void CreateFile(View view) {
EditText ed = findViewById(R.id.editTextTextPersonName);
String data = ed.getText().toString();
fos = null;
try {
// get a outputstream
fos =openFileOutput("mydemofile",MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
// write the file
fos.write(data.getBytes());
textView.setText("File Written");
} catch (IOException e) {
e.printStackTrace();
}
finally {
if (fos != null){
try {
// close the stream
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//user clicks read file button
public void ReadFile(View view) throws IOException {
StringBuilder mytext = new StringBuilder();
InputStream inputStream = null;
try {
inputStream = openFileInput("mydemofile");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//since we'll read bytes and bytes are in the Integers.
int read;
while ((read=inputStream.read()) != -1){
mytext.append((char)read);
}
textView.setText(mytext);
}
}
EXAMPLE 2 :
package com.deepesh.exampleapp4;
import androidx.appcompat.app.AppCompatActivity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import static android.content.ContentValues.TAG;
public class MainActivity extends AppCompatActivity {
TextView textView;
EditText editText;
String FILENAME = "my_internal_file";
FileOutputStream fos;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView1);
editText = findViewById(R.id.editText1);
String internal_dir_path = getFilesDir().getAbsolutePath();
Log.d(TAG, "Internal Directory : " + internal_dir_path);
}
public void StoreData(View view) {
String data = editText.getText().toString();
// Creating new file if not found
try {
fos = openFileOutput(FILENAME,MODE_PRIVATE);
}catch (FileNotFoundException e){
e.printStackTrace();
}
// Writing data to the file
try {
fos.write(data.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
// Closing the outputstream
if (fos !=null){
try {
fos.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
public void AcessData(View view) throws IOException {
StringBuilder stringBuilder = new StringBuilder();
InputStream inputStream = null;
// Getting inputstream to file
try {
inputStream = openFileInput(FILENAME);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// Reading the file
if (inputStream != null){
//since we'll read bytes and bytes are in the Integers.
int read;
while ((read=inputStream.read()) != -1){
stringBuilder.append((char)read);
}
}
textView.setText(stringBuilder);
if (inputStream!=null){
// Closing inputstream
inputStream.close();
}
}
}
-------------------------------------------------------------------------------------------------------
CREATE & WRITE A BINARY (Image ) FILE:
You can convert any media file to binary and store them in the Internal storage.
That includes Images,Videos,Songs etc.
Images are mostly stored in the ASSETS FOLDER but sometimes they are also stored in the DRAWABLE FOLDER.
use getAssets() if you have stored the file in Assets folder
use getDrawable() - if you have stored the file in Drawable folder
package com.example.internalstorageapp;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class MainActivity extends AppCompatActivity {
TextView textView;
FileOutputStream fos;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
//There is only one directory for internal storage for a app.
// this gets the absolute path of Internal storage directory.
String path = getFilesDir().getAbsolutePath();
textView.setText(path);
}
//User click the Create File button
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public void CreateFile(View view) {
// if you have stored in Assets folder , use this variable.
Bitmap data = getImageInAssetsFolder();
//get the image from drawable folder.
BitmapDrawable same_data = (BitmapDrawable) getDrawable(R.drawable.atom);
fos = null;
try {
// get a outputstream
fos =openFileOutput("atom.png",MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// Converts the file into binary and stores in the internal storage.
//takes format of the file & the % of quality to keep ,
// and also the outputstream.
try {
data.compress(Bitmap.CompressFormat.PNG,50,fos);
textView.setText("Binary File written");
}
catch (Exception e){
Toast.makeText(this, "Error occured", Toast.LENGTH_SHORT).show();
}
if (fos != null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private Bitmap getImageInAssetsFolder() {
Bitmap image = null;
//opens a inputstream at the image location
InputStream inputStream = null;
try {
inputStream = getAssets().open("atom.png");
} catch (IOException e) {
e.printStackTrace();
}
//reads the image and returns it in the bitmap format.
// You can also read an Image from a URL
image = BitmapFactory.decodeStream(inputStream);
return image;
}
}
-------------------------------------------------------------------------------------------------------
READ A BINARY FILE :
package com.example.internalstorageapp;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class MainActivity extends AppCompatActivity {
ImageView imageView;
TextView textView;
FileOutputStream fos;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
imageView = findViewById(R.id.imageView1);
//There is only one directory for internal storage for a app.
// this gets the absolute path of Internal storage directory.
String path = getFilesDir().getAbsolutePath();
textView.setText(path);
}
//User click the Create File button
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public void CreateFile(View view) {
// if you have stored in Assets folder , use this variable.
Bitmap data = getImageInAssetsFolder();
//get the image from drawable folder.
BitmapDrawable same_data = (BitmapDrawable) getDrawable(R.drawable.tiger);
fos = null;
try {
// get a outputstream
fos =openFileOutput("tiger.jpg",MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// Converts the file into binary and stores in the internal storage.
//takes format of the file & the % of quality to keep ,
// and also the outputstream.
try {
data.compress(Bitmap.CompressFormat.JPEG,100,fos);
textView.setText("Binary File written");
}
catch (Exception e){
Toast.makeText(this, "Error occured", Toast.LENGTH_SHORT).show();
}
if (fos != null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private Bitmap getImageInAssetsFolder() {
Bitmap image = null;
//opens a inputstream at the image location
InputStream inputStream = null;
try {
inputStream = getAssets().open("tiger.jpg");
} catch (IOException e) {
e.printStackTrace();
}
//reads the image and returns it in the bitmap format.
// You can also read an Image from a URL
image = BitmapFactory.decodeStream(inputStream);
return image;
}
public void ReadFile(View view) {
Bitmap bitmap;
InputStream inputStream = null;
try {
inputStream=openFileInput("tiger.jpg");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//reads the bitmap image at the given inputstream.
bitmap = BitmapFactory.decodeStream(inputStream);
imageView.setImageBitmap(bitmap);
}
}
-------------------------------------------------------------------------------------------------------
List all the files & Delete specific Files :
//user clicks button
public boolean DeletemyFile(View view) {
// deleteFile() - takes filename to delete & returns boolean
return deleteFile("mydemofile");
}
//user clicks button
public void ListAllFiles(View view) {
//fileList() - returns a string array
// containing names of all the files created
String[] allfileslist = fileList();
for (String file : allfileslist){
textView.append(file+"\n");
}
}
-------------------------------------------------------------------------------------------------------
useful video :
https://www.youtube.com/watch?v=-GnvfOPtORk&list=PLj76U7gxVixSMap8f38ph5cMjeFB0NSfW&index=8
CREATE CUSTOM DIRECTORIES:
By default android creates and stores all the Internal file storage into one specific directory called "Files".
But if you want to create a seperate directory on internal storage , you can create one and also create files inside that custom directory.
public void CreateDirectory(View view) {
// gets the path to the given directory , else creates if not found.
File path = getDir("My_custom_dir",MODE_PRIVATE);
// create new file if not found.
File file = new File(path,"mytestfile.txt");
String data = "This is a dummy data";
// write data to file
try {
FileOutputStream outputStream = new FileOutputStream(file);
outputStream.write(data.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
public void ReadCustomDirectoryFile(View view) {
// gets the path to the given directory , else creates if not found.
File path = getDir("My_custom_dir",MODE_PRIVATE);
// create new file if not found.
File file = new File(path,"mytestfile.txt");
if (file.exists()){
Toast.makeText(this, "File available", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this, "File Not found", Toast.LENGTH_SHORT).show();
}
}
You can check the Device file manager to see the custom directory.
---------------------------------------------------------------------------------------------
XML code for 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">
<Button
android:id="@+id/create_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="49dp"
android:onClick="CreateFile"
android:layout_marginLeft="49dp"
android:text="Create File"
app:layout_constraintBottom_toBottomOf="@+id/read_button"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="@+id/read_button" />
<Button
android:id="@+id/delete_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="45dp"
android:text="Delete File"
app:layout_constraintBottom_toTopOf="@+id/create_button"
app:layout_constraintEnd_toEndOf="@+id/create_button"
app:layout_constraintStart_toStartOf="@+id/create_button" />
<Button
android:id="@+id/file_list_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="45dp"
android:text="File list"
app:layout_constraintBottom_toTopOf="@+id/read_button"
app:layout_constraintStart_toStartOf="@+id/read_button" />
<Button
android:id="@+id/read_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="67dp"
android:layout_marginRight="67dp"
android:layout_marginBottom="79dp"
android:text="Read File"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
<EditText
android:id="@+id/editTextTextPersonName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="52dp"
android:ems="10"
android:hint="Enter something..."
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="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="176dp"
android:layout_marginBottom="176dp"
android:gravity="center"
android:text="File Path comes here"
android:textSize="23sp"
app:layout_constraintBottom_toTopOf="@+id/delete_button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>







Comments
Post a Comment