Android External Storage Example(Read/Write)

By | December 30, 2013

In the Previous Tutorial we have seen an example on android internal storage , in this tutorial we will see an example on external storage, here in external storage we  save application data to SD card so there is no security enforced upon the external stored file because all applications can read and write files placed on the external storage and even the user can remove them .

Android External Storage

Here In this tutorial we will see a sample example in which firstly we get the data entered by user from EditText and save this data when Save Button is clicked and finally read the data which is saved into the file and display it to TextView when Load Button is clicked .

For writing and reading to and from a file we are making using of FileOutputStream  and  FileInputStream classes of  java.io  package respectively .

Lets See An Example

Project Detail

Project Name ExternalStorage
Package com.pavan.externalstorage
Minimum SDK API 8
Target SDK API 17
Theme Holo Light with Dark Action Bar

1. XML Layout

file:- activity_main.xml

<RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android”
    xmlns:tools=”http://schemas.android.com/tools”
    android:layout_width=”match_parent”
    android:layout_height=”match_parent”
    android:paddingBottom=”@dimen/activity_vertical_margin”
    android:paddingLeft=”@dimen/activity_horizontal_margin”
    android:paddingRight=”@dimen/activity_horizontal_margin”
    android:paddingTop=”@dimen/activity_vertical_margin”
    tools:context=”.MainActivity” >

    <EditText
        android:id=”@+id/et_data_id”
        android:layout_width=”wrap_content”
        android:layout_height=”wrap_content”
        android:layout_alignParentTop=”true”
        android:layout_centerHorizontal=”true”
        android:layout_marginTop=”25dp”
        android:ems=”10″ >

        <requestFocus />
    </EditText>

    <Button
        android:id=”@+id/load_bt_id”
        android:layout_width=”wrap_content”
        android:layout_height=”wrap_content”
        android:layout_alignBaseline=”@+id/save_bt_id”
        android:layout_alignBottom=”@+id/save_bt_id”
        android:layout_alignRight=”@+id/et_data_id”
        android:text=”Load”
        android:visibility=”invisible” />

    <Button
        android:id=”@+id/save_bt_id”
        android:layout_width=”wrap_content”
        android:layout_height=”wrap_content”
        android:layout_alignLeft=”@+id/et_data_id”
        android:layout_below=”@+id/et_data_id”
        android:layout_marginTop=”25dp”
        android:text=”Save” />

    <TextView
        android:id=”@+id/tv_data_id”
        android:layout_width=”wrap_content”
        android:layout_height=”wrap_content”
        android:layout_below=”@+id/load_bt_id”
        android:layout_centerHorizontal=”true”
        android:layout_marginTop=”15dp”
        android:text=””
        android:textSize=”20dp” />

</RelativeLayout>

2. Activity

file:- MainActivity.java

package com.pavan.externalstorage;

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

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {

 EditText et_data;
 Button save_bt, load_bt;
 TextView tv_data;

 String FILENAME = “myfile”;

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

  initializeViews();

  save_bt.setOnClickListener(this);
  load_bt.setOnClickListener(this);

 }

 private void initializeViews() {
  et_data = (EditText) findViewById(R.id.et_data_id);
  save_bt = (Button) findViewById(R.id.save_bt_id);
  load_bt = (Button) findViewById(R.id.load_bt_id);
  tv_data = (TextView) findViewById(R.id.tv_data_id);

 }

 @Override
 public void onClick(View v) {

  switch (v.getId()) {
  // Writing Data to file
  case R.id.save_bt_id:
   String data = et_data.getText().toString();
   int len = data.length();

   if (len == 0) {
    Toastmessage(“Please Enter The Data”);

   } else {
    try {

     File myFile = new File(“/sdcard/” + FILENAME);
     myFile.createNewFile();
     FileOutputStream fos = new FileOutputStream(myFile);

     fos.write(data.getBytes());
     fos.close();

     Toastmessage(“Data Saved Inside File ” + FILENAME);

     load_bt.setVisibility(View.VISIBLE);

    } catch (FileNotFoundException e) {

     e.printStackTrace();
    } catch (IOException e) {

     e.printStackTrace();
    }
   }

   break;

  // Reading Data From File
  case R.id.load_bt_id:

   String read_data = null;

   try {
    File myFile = new File(“/sdcard/” + FILENAME);
    FileInputStream fis = new FileInputStream(myFile);

    byte[] dataArray = new byte[fis.available()];
    while (fis.read(dataArray) != -1) {
     read_data = new String(dataArray);
    }
    fis.close();

    tv_data.setText(read_data);

   } catch (FileNotFoundException e) {

    e.printStackTrace();
   } catch (IOException e) {

    e.printStackTrace();
   }

   break;
  }

 }

 void Toastmessage(String msg) {
  Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
 }

}

3. Manifest

You need to provide the WRITE_EXTERNAL_STORAGE permission inside the manifest file.

file:- AndroidManifest.xml

<?xml version=”1.0″ encoding=”utf-8″?>
<manifest xmlns:android=”http://schemas.android.com/apk/res/android”
    package=”com.pavan.externalstorage”
    android:versionCode=”1″
    android:versionName=”1.0″ >

    <uses-sdk
        android:minSdkVersion=”8″
        android:targetSdkVersion=”17″ />

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

    <application
        android:allowBackup=”true”
        android:icon=”@drawable/ic_launcher”
        android:label=”@string/app_name”
        android:theme=”@style/AppTheme” >
        <activity
            android:name=”com.pavan.externalstorage.MainActivity”
            android:label=”@string/app_name” >
            <intent-filter>
                <action android:name=”android.intent.action.MAIN” />

                <category android:name=”android.intent.category.LAUNCHER” />
            </intent-filter>
        </activity>
    </application>

</manifest>

4. RUN

Android External Storage Read Write

  • @rhalf
    By default the .txt file extension is added to file BcoZ as we are saving text data

  • sir can we add an extension to the file?

  • i want to extension is .txt and doc. and .pdf file format. how it's possible and what are the jar file i added

  • Can you show me how to get content from wordpress into listview anh detail view? Thanks. I have difficulty on this. Thanks