save data to sd card in android

In android you can save data by using the shared preference and files. But if the data size is much large, then using files or shared preferences is not a suitable option. You can save a large data from an android application into the external sd card available in that device. By using the external sd card for saving the large data, you got the following advantages.

1. You can share the app data to other devices.
2. You can save data of any size by expanding the external sd card memory size.
3. You can easily backup your data.

In an android application for saving data into the external sd card you have to follow the steps given bellow.


Step 1: Obtain the path of the sd card


Use the getExternalStorageDirectory() method for getting the full path of the sd card. For real devices it return "/sdcard" and "/mnt/sdcard" for android virtual devices(AVD).

Example:  File sdcard = Environment.getExternalStorageDirectory();


Step 2: Create a directory on the sd card

In sd card, you need to create a directory for the saving the file. Use the mkdirs() method for creating the directory. In the example given bellow "MyDirectory" is the name of the directory.  

Example:    File directory = new File(sdcard.getAbsolutePath()+ "/MyDirectory");
  directory.mkdirs(); 

Step 3: Create a file on the directory

You need to create a file with a valid name in that directory using the File class object.

Example : File file = new File(directory,"textfile.txt"); 
Now you can perform the read and write operations on the file using the FileOutputStream and FileInputStream objects with the  help of OutputStreamWriter and InputStreamReader objects.  

Step 4 : Set the WRITE_EXTERNAL_STORAGE permission on AndroidManifest.xml  file

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

Watch Video Tutorial Of this Topic


activity_main.xml
1:  <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
2: xmlns:tools="http://schemas.android.com/tools"
3: android:layout_width="match_parent"
4: android:layout_height="match_parent"
5: android:paddingBottom="@dimen/activity_vertical_margin"
6: android:paddingLeft="@dimen/activity_horizontal_margin"
7: android:paddingRight="@dimen/activity_horizontal_margin"
8: android:paddingTop="@dimen/activity_vertical_margin"
9: tools:context=".MainActivity" >
10: <EditText
11: android:id="@+id/msg"
12: android:layout_width="wrap_content"
13: android:layout_height="wrap_content"
14: android:layout_alignParentTop="true"
15: android:layout_centerHorizontal="true"
16: android:layout_marginTop="20dp"
17: android:ems="10"
18: android:hint="Enter a message"
19: >
20: <requestFocus />
21: </EditText>
22: <Button
23: android:id="@+id/LOAD"
24: android:layout_width="wrap_content"
25: android:layout_height="wrap_content"
26: android:layout_alignLeft="@+id/SAVE"
27: android:layout_below="@+id/SAVE"
28: android:layout_marginTop="46dp"
29: android:text="LOAD DATA" />
30: <Button
31: android:id="@+id/SAVE"
32: android:layout_width="wrap_content"
33: android:layout_height="wrap_content"
34: android:layout_below="@+id/msg"
35: android:layout_centerHorizontal="true"
36: android:layout_marginTop="23dp"
37: android:text="SAVE DATA" />
38: </RelativeLayout>

MainActivity.java
1:  package com.filedemo;  
2: import java.io.File;
3: import java.io.FileInputStream;
4: import java.io.FileNotFoundException;
5: import java.io.FileOutputStream;
6: import java.io.IOException;
7: import java.io.InputStreamReader;
8: import java.io.OutputStreamWriter;
9: import android.app.Activity;
10: import android.os.Bundle;
11: import android.os.Environment;
12: import android.view.Menu;
13: import android.view.View;
14: import android.view.View.OnClickListener;
15: import android.widget.Button;
16: import android.widget.EditText;
17: import android.widget.Toast;
18: public class MainActivity extends Activity {
19: Button save,load;
20: EditText message;
21: String Message;
22: int data_block = 100;
23: @Override
24: protected void onCreate(Bundle savedInstanceState) {
25: super.onCreate(savedInstanceState);
26: setContentView(R.layout.activity_main);
27: save=(Button) findViewById(R.id.SAVE);
28: load = (Button) findViewById(R.id.LOAD);
29: message = (EditText) findViewById(R.id.msg);
30: save.setOnClickListener(new OnClickListener() {
31: @Override
32: public void onClick(View v) {
33: // TODO Auto-generated method stub
34: Message = message.getText().toString();
35: try {
36: //FileOutputStream fou = openFileOutput("text.txt", MODE_WORLD_READABLE);
37: File sdcard = Environment.getExternalStorageDirectory();
38: File directory = new File(sdcard.getAbsolutePath()+ "/MyDirectory");
39: directory.mkdirs();
40: File file = new File(directory,"textfile.txt");
41: FileOutputStream fou = new FileOutputStream(file);
42: OutputStreamWriter osw = new OutputStreamWriter(fou);
43: try {
44: osw.write(Message);
45: osw.flush();
46: osw.close();
47: Toast.makeText(getBaseContext(), "Data saved", Toast.LENGTH_LONG).show();
48: } catch (IOException e) {
49: // TODO Auto-generated catch block
50: e.printStackTrace();
51: }
52: } catch (FileNotFoundException e) {
53: // TODO Auto-generated catch block
54: e.printStackTrace();
55: }
56: }
57: });
58: load.setOnClickListener(new OnClickListener() {
59: @Override
60: public void onClick(View v) {
61: // TODO Auto-generated method stub
62: try {
63: File sdcard = Environment.getExternalStorageDirectory();
64: File directory = new File(sdcard.getAbsolutePath()+ "/MyDirectory");
65: File file = new File(directory,"textfile.txt");
66: FileInputStream fis = new FileInputStream(file);
67: InputStreamReader isr = new InputStreamReader(fis);
68: char[] data = new char[data_block];
69: String final_data="";
70: int size;
71: try {
72: while((size = isr.read(data))>0)
73: {
74: String read_data = String.copyValueOf(data, 0, size);
75: final_data+= read_data;
76: data = new char[data_block];
77: }
78: Toast.makeText(getBaseContext(), "Message :"+final_data, Toast.LENGTH_LONG).show();
79: } catch (IOException e) {
80: // TODO Auto-generated catch block
81: e.printStackTrace();
82: }
83: } catch (FileNotFoundException e) {
84: // TODO Auto-generated catch block
85: e.printStackTrace();
86: }
87: }
88: });
89: }
90: @Override
91: public boolean onCreateOptionsMenu(Menu menu) {
92: // Inflate the menu; this adds items to the action bar if it is present.
93: getMenuInflater().inflate(R.menu.main, menu);
94: return true;
95: }
96: }

AndroidManifest.xml 
1:  <?xml version="1.0" encoding="utf-8"?>  
2: <manifest xmlns:android="http://schemas.android.com/apk/res/android"
3: package="com.filedemo"
4: android:versionCode="1"
5: android:versionName="1.0" >
6: <uses-sdk
7: android:minSdkVersion="8"
8: android:targetSdkVersion="17" />
9: <application
10: android:allowBackup="true"
11: android:icon="@drawable/ic_launcher"
12: android:label="@string/app_name"
13: android:theme="@style/AppTheme" >
14: <activity
15: android:name="com.filedemo.MainActivity"
16: android:label="@string/app_name" >
17: <intent-filter>
18: <action android:name="android.intent.action.MAIN" />
19: <category android:name="android.intent.category.LAUNCHER" />
20: </intent-filter>
21: </activity>
22: </application>
23: <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
24: </manifest>