Write To and Read From SD Card

Introduction

 
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 an 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.                     File myfile = new File(dir, "MyTextFile.txt");    
  27.     
  28.                     try {    
  29.                         myfile.createNewFile();    
  30.                         try {    
  31.                             FileOutputStream fout = new FileOutputStream(myfile);    
  32.                             PrintWriter pw = new PrintWriter(fout);    
  33.                             pw.println("Name=Pankaj Kumar Choudhary");    
  34.                             pw.println("\r\n" + "City=Alwar Rajasthan");    
  35.                             pw.println("\r\n" + "Occupation=Student");    
  36.                             pw.println("\r\n" + "Branch=Computer(CSE)");    
  37.                             pw.println("\r\n" + "Semester=7th");    
  38.                             pw.flush();    
  39.                             pw.close();    
  40.                             fout.close();    
  41.                             Toast.makeText(getApplicationContext(), "File Written successfully", Toast.LENGTH_LONG).show();    
  42.                         } catch (Exception e) {    
  43.                             Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();    
  44.                             //tv.setText(e.toString());    
  45.                         }    
  46.     
  47.     
  48.                     } catch (IOException e1) {    
  49.                         // TODO Auto-generated catch block    
  50.                         e1.printStackTrace();    
  51.                     }    
  52.     
  53.                 } else {    
  54.                     Toast.makeText(getApplicationContext(), "Media is not mounted", Toast.LENGTH_SHORT).show();    
  55.                 }    
  56.     
  57.             }    
  58.         });    
  59.         Read.setOnClickListener(new View.OnClickListener() {    
  60.     
  61.             @Override    
  62.             public void onClick(View arg0) {    
  63.                 // TODO Auto-generated method stub    
  64.     
  65.                 File f = Environment.getExternalStorageDirectory();    
  66.                 //f.getAbsolutePath()    
  67.                 File finalPath = new File(f.getAbsolutePath(), "/My_File/MyTextFile.txt");    
  68.                 String lines = null;    
  69.                 TextView t = (TextView) findViewById(R.id.textView1);    
  70.                 try {    
  71.                     FileInputStream fin = new FileInputStream(finalPath);    
  72.                     BufferedReader myReader = new BufferedReader(new InputStreamReader(fin));    
  73.     
  74.                     while ((lines = myReader.readLine()) != null) {    
  75.                         t.append(lines + "\r\n");    
  76.                     }    
  77.                     myReader.close();    
  78.                     Toast.makeText(getApplicationContext(), "File has been read successfully", Toast.LENGTH_LONG).show();    
  79.                 } catch (Exception e) {    
  80.                     t.append(finalPath.getPath() + "\n" + e.toString());    
  81.                     Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();    
  82.                 }    
  83.     
  84.             }    
  85.         });    
  86.     }    
  87. }   
    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 the 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 convenient 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.