Android Internal Storage with Examples

In android, we have different storage options such as shared preferences, internal storage, external storage, SQLite storage, etc. to store and retrieve the application data based on our requirements.

 

In previous chapters, we learned how to use Shared Preferences and now we will see how to use the Internal Storage option to store and retrieve the data from the device’s internal memory.

 

In android, Internal Storage is useful to store the data files locally on the device’s internal memory using a FileOutputStream object. After storing the data files in device internal storage, we can read the data file from the device using a FileInputStream object.

 

The data files saved in the internal are managed by an android framework and it can be accessed anywhere within the app to read or write data into the file, but it’s not possible to access the file from any other app so it’s secured. When the user uninstalls the app, automatically these data files will be removed from the device internal storage.

Write a File to Internal Storage

By using the android FileOutputStream object openFileOutput method, we can easily create and write data to a file in a device’s internal storage.

 

Following is the code snippet to create and write a private file to the device's internal memory.

 

String FILENAME = "user_details";
String name =
"suresh";

FileOutputStream fstream = openFileOutput(FILENAME, Context.
MODE_PRIVATE);
fstream.write(name.getBytes());
fstream.close();

If you observe above code, we are creating and writing a file in device internal storage by using FileOutputStream object openFileOutput method with file name and MODE_PRIVATE mode to make the file private to our application. We used write() method to write the data in file and used close() method to close the stream.

 

In android, we have different modes such as MODE_APPEND, MODE_WORLD_READBLE, MODE_WORLD_WRITEABLE, etc. to use it in our application based on your requirements.

 

Apart from the above methods write() and close()FileOutputStream object is having other methods, those are

 

MethodDescription
getChannel() It returns the unique FileChannel object associated with this file output stream.
getFD() It returns the file descriptor which is associated with the stream.
write(byte[] b, int off, int len) It writes len bytes from the specified byte array starting at offset off to the file output stream.

Read a File from Internal Storage

By using the android FileInputStream object openFileInput method, we can easily read the file from the device’s internal storage.

 

Following is the code snippet to read data from a file that is in the device’s internal memory.

 

String FILENAME = "user_details";
FileInputStream
fstream = openFileInput(FILENAME);
StringBuffer sbuffer =
new StringBuffer();
int i;
while ((i = fstream.read())!= -1){
    sbuffer.append((
char)i);
}
fstream.close();

If you observe above code, we are reading a file from device internal storage by using FileInputStream object openFileInput method with file name. We used read() method to read one character at a time from the file and used close() method to close the stream.

 

Apart from the above methods read() and close(), FileInputStream object is having other methods, those are

 

MethodDescription
getChannel() It returns the unique FileChannel object associated with this file output stream.
getFD() It returns the file descriptor which is associated with the stream.
read(byte[] b, int off, int len) It reads len bytes of data from the specified file input stream into an array of bytes.

Now we will see how to save files directly on the device’s internal memory and read the data files from device internal memory by using FileOutputStream and FileInputStream objects in android application with examples.

Android Internal Storage Example

Following is the example of storing and retrieving the data files from the device’s internal memory by using FileOutputStream and FileInputStream objects.

 

Create a new android application using android studio and give names as InternalStorageExample. In case if you are not aware of creating an app in android studio check this article Android Hello World App.

 

Once we create an application, open activity_main.xml file from \res\layout folder path and write the code like as shown below.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   
android:orientation="vertical" android:layout_width="match_parent"
   
android:layout_height="match_parent">
    <
TextView
       
android:id="@+id/fstTxt"
       
android:layout_width="wrap_content"
       
android:layout_height="wrap_content"
       
android:layout_marginLeft="100dp"
        
android:layout_marginTop="150dp"
       
android:text="UserName" />
    <
EditText
       
android:id="@+id/txtName"
       
android:layout_width="wrap_content"
       
android:layout_height="wrap_content"
       
android:layout_marginLeft="100dp"
       
android:ems="10"/>
    <TextView
       
android:id="@+id/secTxt"
       
android:layout_width="wrap_content"
       
android:layout_height="wrap_content"
       
android:text="Password"
       
android:layout_marginLeft="100dp" />
    <
EditText
       
android:id="@+id/txtPwd"
       
android:inputType="textPassword"
       
android:layout_width="wrap_content"
       
android:layout_height="wrap_content"
       
android:layout_marginLeft="100dp"
       
android:ems="10" />
    <
Button
       
android:id="@+id/btnSave"
       
android:layout_width="wrap_content"
       
android:layout_height="wrap_content"
       
android:layout_marginLeft="100dp"
       
android:text="Save" />
</
LinearLayout>

Now we will create another layout resource file details.xml in \res\layout path to get the first activity (activity_main.xml) details in second activity file for that right click on your layout folder à Go to New à select Layout Resource File and give name as details.xml.

 

Once we create a new layout resource file details.xml, open it and write the code like as shown below

details.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   
android:orientation="vertical" android:layout_width="match_parent"
   
android:layout_height="match_parent">
    <
TextView
       
android:layout_width="wrap_content"
       
android:layout_height="wrap_content"
       
android:id="@+id/resultView"
       
android:layout_gravity="center"
       
android:layout_marginTop="170dp"
       
android:textSize="20dp"/>
    <
Button
       
android:id="@+id/btnBack"
       
android:layout_width="wrap_content"
       
android:layout_height="wrap_content"
        
android:layout_gravity="center"
       
android:layout_marginTop="20dp"
       
android:text="Back" />
</
LinearLayout>

Now open your main activity file MainActivity.java from \java\com.tutlane.internalstorageexample path and write the code like as shown below

MainActivity.java

package com.tutlane.internalstorageexample;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {
    EditText
uname, pwd;
    Button
saveBtn;
    FileOutputStream
fstream;
    Intent
intent;
   
@Override
   
protected void onCreate(Bundle savedInstanceState) {
       
super.onCreate(savedInstanceState);
        setContentView(R.layout.
activity_main);
       
uname = (EditText)findViewById(R.id.txtName);
       
pwd = (EditText)findViewById(R.id.txtPwd);
       
saveBtn = (Button)findViewById(R.id.btnSave);
       
saveBtn.setOnClickListener(new View.OnClickListener() {
           
@Override
           
public void onClick(View v) {
                String username =
uname.getText().toString()+"\n";
                String password =
pwd.getText().toString();
               
try {
                   
fstream = openFileOutput("user_details", Context.MODE_PRIVATE);
                    
fstream.write(username.getBytes());
                   
fstream.write(password.getBytes());
                   
fstream.close();
                    Toast.makeText(getApplicationContext(),
"Details Saved Successfully",Toast.LENGTH_SHORT).show();
                   
intent = new Intent(MainActivity.this,DetailsActivity.class);
                    startActivity(
intent);
                }
catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

If you observe above code, we are taking entered username and password details and saving it in device local file and redirecting the user to another activity.

 

Now we will create another activity file DetailsActivity.java in \java\com.tutlane.internalstorageexample path to show the details from device internal storage for that right-click on your application folder à Go to New à select Java Class and give name as DetailsActivity.java.

 

Once we create a new activity file DetailsActivity.java, open it and write the code like as shown below

DetailsActivity.java

package com.tutlane.internalstorageexample;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * Created by tutlane on 04-01-2018.
 */

public class DetailsActivity extends AppCompatActivity {
    FileInputStream
fstream;
    Intent
intent;
   
@Override
   
protected void onCreate(Bundle savedInstanceState) {
       
super.onCreate(savedInstanceState);
        setContentView(R.layout.
details);
        TextView result = (TextView)findViewById(R.id.
resultView);
        Button back = (Button)findViewById(R.id.
btnBack);
       
try {
           
fstream = openFileInput("user_details");
            StringBuffer sbuffer =
new StringBuffer();
           
int i;
           
while ((i = fstream.read())!= -1){
                sbuffer.append((
char)i);
            }
           
fstream.close();
            String details[] = sbuffer.toString().split(
"\n");
            result.setText(
"Name: "+ details[0]+"\nPassword: "+details[1]);
        }
catch (FileNotFoundException e) {
            e.printStackTrace();
        }
catch (IOException e) {
            e.printStackTrace();
        }
        back.setOnClickListener(
new View.OnClickListener() {
           
@Override
           
public void onClick(View v) {
               
intent = new Intent(DetailsActivity.this,MainActivity.class);
                startActivity(
intent);
            }
        });
    }
}

Now we need to add this newly created activity in AndroidManifest.xml file in like as shown below.

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   
package="com.tutlane.internalstorageexample">
    <
application
       
android:allowBackup="true"
       
android:icon="@mipmap/ic_launcher"
       
android:label="@string/app_name"
       
android:roundIcon="@mipmap/ic_launcher_round"
       
android:supportsRtl="true"
       
android:theme="@style/AppTheme">
        <
activity android:name=".MainActivity">
            <
intent-filter>
                <
action android:name="android.intent.action.MAIN" />
                <
category android:name="android.intent.category.LAUNCHER" />
            </
intent-filter>
        </
activity>
        <
activity android:name=".DetailsActivity" android:label="Internal Storage - Details"></activity>
    </
application>
</
manifest>

If you observe above example, we are saving entered details file and redirecting the user to another activity file (DetailsActivity.java) to show the users details and added all the activities in AndroidManifest.xml file.

Output of Android Internal Storage Example

When we run above example in android emulator we will get a result like as shown below

 

Android Internal Storage Example Result

 

If you observe the above result, the entered username and password details are storing in the device’s local memory and redirecting the user to another activity file to show the user details from the internal storage file. After that, if we click on the Back button, it will redirect the user to the login page.

 

This is how we can use the Internal Storage option in android applications to store and retrieve data from device internal memory based on our requirements.