How to read and write files to SDCARD and application SandBox in Android – A complete example?

By | February 14, 2016

Here is a complete example of How to read and write files to SDCARD and application SandBox in Android.

Files Example

First create a new project and inside the mainActivity paste this code.

package com.coderzheaven.filesexample;
 
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.Toast;
 
public class MainActivity extends Activity implements OnClickListener {
 
    EditText edittext;
    Button b1, b2, b3, b4;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         
        edittext = (EditText)findViewById(R.id.ed);
        edittext.setLines(10);
        b1 = (Button)findViewById(R.id.button1);
        b2 = (Button)findViewById(R.id.button2);
        b3 = (Button)findViewById(R.id.button3);
        b4 = (Button)findViewById(R.id.button4);
         
        b1.setOnClickListener(this);
        b2.setOnClickListener(this);
        b3.setOnClickListener(this);
        b4.setOnClickListener(this);       
         
    }
    @Override
    public void onClick(View v) {
        int id = v.getId();
        MyFile file = new MyFile(v.getContext());
         
        switch(id){
            case R.id.button1:
                if(!edittext.getText().toString().trim().equals("")){
                    file.writeToSD(edittext.getText().toString());
                }else{
                    Toast.makeText(v.getContext(), "Please enter some contents for the file", Toast.LENGTH_LONG).show();
                }
                break;
                 
            case R.id.button2:
                edittext.setText(file.readFromSD());
                break;
             
            case R.id.button3:
                if(!edittext.getText().toString().trim().equals("")){
                    file.writeToSandBox(edittext.getText().toString());
                }else{
                    Toast.makeText(v.getContext(), "Please enter some contents for the file", Toast.LENGTH_LONG).show();
                }
                break;
                 
            case R.id.button4:
                edittext.setText(file.readFromSandBox());
                break;
        }
         
         
         
    }
 
}

Now create another class named MyFile.java and copy this code into it.

package com.coderzheaven.filesexample;
 
import java.io. BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
 
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Environment;
import android.util.Log;
 
public class MyFile {
 
    String TAG = "MyFile";
    Context context;
    public MyFile(Context context){
        this.context = context;
    }
     
    public Boolean writeToSD(String text){
        Boolean write_successful = false;
         File root=null
            try
                // check for SDcard  
                root = Environment.getExternalStorageDirectory(); 
                Log.i(TAG,"path.." +root.getAbsolutePath()); 
       
                //check sdcard permission 
                if (root.canWrite()){ 
                    File fileDir = new File(root.getAbsolutePath()); 
                    fileDir.mkdirs(); 
       
                    File file= new File(fileDir, "samplefile.txt"); 
                    FileWriter filewriter = new FileWriter(file); 
                    BufferedWriter out = new BufferedWriter(filewriter); 
                    out.write(text); 
                    out.close(); 
                    write_successful = true;
                
            } catch (IOException e) { 
                Log.e("ERROR:---", "Could not write file to SDCard" + e.getMessage()); 
                write_successful = false;
            
        return write_successful;
    }
     
    public String readFromSD(){
        File sdcard = Environment.getExternalStorageDirectory();
        File file = new File(sdcard,"samplefile.txt");
        StringBuilder text = new StringBuilder();
        try {
            BufferedReader br = new BufferedReader(new FileReader(file));
            String line;
            while ((line = br.readLine()) != null) {
                text.append(line);
                text.append('\n');
            }
        }
        catch (IOException e) {
        }
        return text.toString();
    }
 
    @SuppressLint("WorldReadableFiles")
    @SuppressWarnings("static-access")
    public Boolean writeToSandBox(String text){
        Boolean write_successful = false;
        try{
            FileOutputStream fOut = context.openFileOutput("samplefile.txt",
                    context.MODE_WORLD_READABLE);
            OutputStreamWriter osw = new OutputStreamWriter(fOut);
            osw.write(text);
            osw.flush();
            osw.close();
        }catch(Exception e){
            write_successful = false;
        }
        return write_successful;
    }
    public String readFromSandBox(){
        String str ="";
        String new_str = "";
        try{
            FileInputStream fIn = context.openFileInput("samplefile.txt");
            InputStreamReader isr = new InputStreamReader(fIn);
            BufferedReader br=new BufferedReader(isr);
            
            while((str=br.readLine())!=null)
            {
                new_str +=str;
                System.out.println(new_str);
            }           
        }catch(Exception e)
        {          
        }
        return new_str;
    }
}

Now the layout for the xml file.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
 
    <EditText
        android:id="@+id/ed"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:lines="5" android:gravity="top|left"
        android:inputType="textMultiLine"
    android:scrollHorizontally="false"
    android:minWidth="10.0dip"
    android:maxWidth="5.0dip"
        android:layout_weight="1"/>
 
    <Button
        android:id="@+id/button1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Write File to SDCARD" />
     
    <Button
        android:id="@+id/button2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Read File from SDCARD" />
     
    <Button
        android:id="@+id/button3"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Write File to Application SandBox" />
     
    <Button
        android:id="@+id/button4"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Read File from Application SandBox" />
 
</LinearLayout>

Note you should give this permission in the AndroidManifest file.

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

OK Done. Now run the project.

To view the files

1. To see the SDCARD
Open File explorer -> expand sdcard (or mnt/sdcard).
2. To see the Application SANDBOX
Open File explorer -> expand data/data/your_package_name/files.

Download
.

Please leave your valuable comments on this post.

Join the Forum discussion on this post

3 thoughts on “How to read and write files to SDCARD and application SandBox in Android – A complete example?

  1. Pingback: How to read a text file that is stored in your application sandbox in ANDROID?

Leave a Reply to Mr Queentin Cancel reply

Your email address will not be published. Required fields are marked *