Write To and Read From SD Card

First, we will create a simple text file and then write some data into this file and finally we will read the data from the text file.

Now we move to the coding part of this article.

XML Code of Activity

  1. <FrameLayout  
  2.     xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     xmlns:tools="http://schemas.android.com/tools"  
  4.         android:id="@+id/container"  
  5.         android:layout_width="match_parent"  
  6.         android:layout_height="match_parent"  
  7.         tools:context="com.example.readwritedataonsdcard.MainActivity"  
  8.         tools:ignore="MergeRootFrame" >  
  9.     <LinearLayout  
  10.         android:layout_width="match_parent"  
  11.         android:layout_height="match_parent"  
  12.         android:orientation="vertical" >  
  13.         <Button  
  14.             android:id="@+id/btnWrite"  
  15.             android:layout_width="222dp"  
  16.             android:layout_height="wrap_content"  
  17.             android:text="@string/Write" />  
  18.         <Button  
  19.             android:id="@+id/btnRead"  
  20.             android:layout_width="222dp"  
  21.             android:layout_height="wrap_content"  
  22.             android:text="@string/Read" />  
  23.         <TextView  
  24.             android:id="@+id/textView1"  
  25.             android:layout_width="304dp"  
  26.             android:layout_height="900dp"  
  27.             android:layout_weight="0.06"  
  28.             android:textAppearance="?android:attr/textAppearanceLarge" />  
  29.     </LinearLayout>  
  30. </FrameLayout>  
After using the preceding XML code our activity will look as in the following:

our activity

In this activity we use two buttons and a TextView (Label):
- The first button is “Write Data”. We will use this button to create a file and write some data in that text file
- The second button is “Read Data”.  We will use this button to read the data from the file and show the data in a TextView (Label).

Take User Permission

This is very important. If we are using a SDCard (Storage Device) in our project, then we must have user-permission, otherwise the system will throw an error of permission denied. We can take user permission using the following code:
  1. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>  
Write this code in your AndroidMainfest.xml file like the following:

XML COde

Now we move to the source code (Java code) of this project. The following is the source code:
  1. public class MainActivity extends ActionBarActivity {  
  2.   
  3.     Button Read;  
  4.     Button Write;@Override  
  5.     protected void onCreate(Bundle savedInstanceState) {  
  6.         super.onCreate(savedInstanceState);  
  7.         setContentView(R.layout.activity_main);  
  8.   
  9.         Read = (Button) findViewById(R.id.btnRead);  
  10.         Write = (Button) findViewById(R.id.btnWrite);  
  11.   
  12.         Write.setOnClickListener(new View.OnClickListener() {  
  13.   
  14.             @Override  
  15.             public void onClick(View arg0) {  
  16.                 // TODO Auto-generated method stub  
  17.   
  18.                 String state = Environment.getExternalStorageState();  
  19.   
  20.                 if (state.equals(Environment.MEDIA_MOUNTED)) {  
  21.                     Toast.makeText(getApplicationContext(), "Media Is Mounted", Toast.LENGTH_SHORT).show();  
  22.                     File f = Environment.getExternalStorageDirectory();  
  23.                     File dir = new File(f.getAbsolutePath() + "/My_File");  
  24.                     dir.mkdirs();  
  25.   
  26.   
  27.   
  28.                     File myfile = new File(dir, "MyTextFile.txt");  
  29.   
  30.                     try {  
  31.                         myfile.createNewFile();  
  32.                         try {  
  33.                             FileOutputStream fout = new FileOutputStream(myfile);  
  34.                             PrintWriter pw = new PrintWriter(fout);  
  35.                             pw.println("Name=Pankaj Kumar Choudhary");  
  36.                             pw.println("\r\n" + "City=Alwar Rajasthan");  
  37.                             pw.println("\r\n" + "Occupation=Student");  
  38.                             pw.println("\r\n" + "Branch=Computer(CSE)");  
  39.                             pw.println("\r\n" + "Semester=7th");  
  40.                             pw.flush();  
  41.                             pw.close();  
  42.                             fout.close();  
  43.                             Toast.makeText(getApplicationContext(), "File Written successfully", Toast.LENGTH_LONG).show();  
  44.                         } catch (Exception e) {  
  45.                             Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();  
  46.                             //tv.setText(e.toString());  
  47.                         }  
  48.   
  49.   
  50.                     } catch (IOException e1) {  
  51.                         // TODO Auto-generated catch block  
  52.                         e1.printStackTrace();  
  53.                     }  
  54.   
  55.                 } else {  
  56.                     Toast.makeText(getApplicationContext(), "Media is not mounted", Toast.LENGTH_SHORT).show();  
  57.                 }  
  58.   
  59.   
  60.   
  61.   
  62.             }  
  63.         });  
  64.         Read.setOnClickListener(new View.OnClickListener() {  
  65.   
  66.             @Override  
  67.             public void onClick(View arg0) {  
  68.                 // TODO Auto-generated method stub  
  69.   
  70.                 File f = Environment.getExternalStorageDirectory();  
  71.                 //f.getAbsolutePath()  
  72.                 File finalPath = new File(f.getAbsolutePath(), "/My_File/MyTextFile.txt");  
  73.                 String lines = null;  
  74.                 TextView t = (TextView) findViewById(R.id.textView1);  
  75.                 try {  
  76.                     FileInputStream fin = new FileInputStream(finalPath);  
  77.                     BufferedReader myReader = new BufferedReader(new InputStreamReader(fin));  
  78.   
  79.                     while ((lines = myReader.readLine()) != null) {  
  80.                         t.append(lines + "\r\n");  
  81.                     }  
  82.                     myReader.close();  
  83.                     Toast.makeText(getApplicationContext(), "File has been read successfully", Toast.LENGTH_LONG).show();  
  84.                 } catch (Exception e) {  
  85.                     t.append(finalPath.getPath() + "\n" + e.toString());  
  86.                     Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();  
  87.                 }  
  88.   
  89.             }  
  90.         });  
  91.     }  
  92. }  
Now I will explain the preceding code in a number of sections for a better understanding:

Code Section 1
  1. String state = Environment.getExternalStorageState();  
  2.   
  3. if (state.equals(Environment.MEDIA_MOUNTED)) {  
  4.     Toast.makeText(getApplicationContext(), "Media Is Mounted", Toast.LENGTH_SHORT).show();  
  5.     File f = Environment.getExternalStorageDirectory();  
  6.     File dir = new File(f.getAbsolutePath() + "/My_File");  
  7.     dir.mkdirs();  
  8. }  
In the preceding code we get the information about the external storage of our device using the getExternalStorageState() method. This method returns the information about the primary external storage directory like whether the external storage device is mounted. If the external storage device is mounted then we will show a message that “Media Is Mounted” using the Toast.makeText() method like the following:

Media Is Mounted

Then we get the full path of the external storage device (SD Card) using the getExternalStorageDirectory() method. Now we will make a new directory (folder) in the SD Card using the mkdirs() method and assign a name. Here we will create a folder with the name “My_File”.

Code Section 2
  1. File myfile = new File(dir, "MyTextFile.txt");  
  2.   
  3. try {  
  4.     myfile.createNewFile();  
  5.     try {  
  6.         FileOutputStream fout = new FileOutputStream(myfile);  
  7.         PrintWriter pw = new PrintWriter(fout);  
  8.         pw.println("Name=Pankaj Kumar Choudhary");  
  9.         pw.println("\r\n" + "City=Alwar Rajasthan");  
  10.         pw.println("\r\n" + "Occupation=Student");  
  11.         pw.println("\r\n" + "Branch=Computer(CSE)");  
  12.         pw.println("\r\n" + "Semester=7th");  
  13.         pw.flush();  
  14.         pw.close();  
  15.         fout.close();  
  16.         Toast.makeText(getApplicationContext(), "File Written successfully", Toast.LENGTH_LONG).show();  
  17.     }  
  18. }
In the preceding code we create a new TextFile using the createNewFile method. We use an object of the FileOutputStream class. FileOutputStream creates an OutputStream that we can use to write bytes to a file. In other words FileOutputStream is used to write binary data to a file. We use a parameterized constructor of the FileOutputStream class and pass the name of file as parameter. So the object of the FileOutputStream class will create an OutputStream for the “MyTextFile.txt” file. We create an object of PrintWriter class. This class provides a convenience method for printing common data types in a human readable format. We write some data into our text file using the “println” method. Finally we will show a message of file successfully written.

Conclusion

I can summarize all the operations in the following. We are writing our data in a PrintWriter class object using the println method. The PrintWriter class inserts all the data into a FileOutputStream class object and the FileOutputStream's object converts the data into byte code form and inserts the data into our textfile.

textfile

After the file is successfully written, check the storage of our device. We will find that “MyTextFile.txt” has been created in the sdcard.

MyTextFile

Now we will check the data of this text file.

notepad

We can see that this text file contains the same data that we wrote in the preceding. Now I will explain how to read this data and show in a TextView.

Code Section 3
  1. File f = Environment.getExternalStorageDirectory();  
  2. //f.getAbsolutePath()  
  3. File finalPath = new File(f.getAbsolutePath(), "/My_File/MyTextFile.txt");  
  4. String lines = null;  
  5. TextView t = (TextView) findViewById(R.id.textView1);  
  6. try {  
  7.     FileInputStream fin = new FileInputStream(finalPath);  
  8.     BufferedReader myReader = new BufferedReader(new InputStreamReader(fin));  
  9.   
  10.     while ((lines = myReader.readLine()) != null) {  
  11.         t.append(lines + "\r\n");  
  12.     }  
  13.     myReader.close();  
  14.     Toast.makeText(getApplicationContext(), "File has been read successfully", Toast.LENGTH_LONG).show();  
  15. }  
In the preceding code we used the getExternalStorageDirectory method. This method returns information about the primary external storage directory. Here the primary external storage device is the sdcard. In the next line we create an object of the File class. We pass two parameters in the File class constructor. The first is the absolute path of the external storage device and the second is the path of our text file in the sdcard. We also created an object of the FileInputStream class. The FileInputStream class is used to read a byte of data from a file. We pass the path of the file as a parameter in the FileInputStream class constructor.

We create an object of the BufferedReader class. The BufferedReader class wraps an existing Reader and buffers the input. In other words the BufferedReader class retrieves data from a reader (here the reader is FileInputStream) and stores it in a buffer.

Now we can easily read data from the buffer using the readline method. In the preceding code we read data line by line from the buffer and appended (inserted) this data into the TextView.

So when we click on the “Read Data” button, the output will be the following:

Read Data

Thanks for reading my article. In the next article I will explain a new topic on Android.

Up Next
    Ebook Download
    View all
    Learn
    View all