Reading and Writing data from Android Device's storage using java

Hello guys 


In this blog im going to explain how to read and write data from and to an android device's storage using java

Step 1:


Create An Android Project


Step 2:



Add the following permissions :


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




Step 3:


I used the following codes for Reading as well as Writing



for writing:

What i have done  is create a folder is the folder doesn't exists and create a file what i have to read if the file doesn't exit.

if the above part is clear then you are ready to write.


public void writeFile() {


final File dir = new File(Environment.getExternalStorageDirectory()
   .getPath() + "/Android/data/" + getPackageName() + "/");  //first  method for specifying the directory structure
  try {
   

   try {
    if (!dir.exists()) {

     dir.mkdirs();  //creates the directory

     Toast.makeText(getBaseContext(), "Directory created",
       Toast.LENGTH_SHORT).show();
     final String filename = "test.txt";

     File file = new File(dir, filename);

     file.createNewFile(); //creates the file

     FileOutputStream fOut = new FileOutputStream(file);
     OutputStreamWriter myOutWriter = new OutputStreamWriter(
       fOut);
     myOutWriter.write(filename);
     myOutWriter.close();
     fOut.close();
    }
   } catch (Exception e) {
    e.printStackTrace();
   }

   Toast.makeText(getBaseContext(), "Done writing SD 'mysdfile.txt'",
     Toast.LENGTH_SHORT).show();
  } catch (Exception e) {
   Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT)
     .show();
  }

 }


// Code for reading the text file:



public void readFile() {

   FileInputStream fIn;
  String result = null, venue = " ";
  try {
   
  File myFile= new File("/sdcard/Android/data/com.example.test/test.txt"); //second  method for specifying the directory structure
   
   fIn = new FileInputStream(myFile);
   BufferedReader reader = new BufferedReader(new InputStreamReader(
     fIn, "UTF-8"), 8);
   StringBuilder sb = new StringBuilder();
   String line = null;
   while ((line = reader.readLine()) != null) {
    sb.append(line + "\n");
   }
   fIn.close();
   result = sb.toString();
   Log.d("result", result);

//What i am doing here is parsing the json data from the text file



    JSONArray ja = new JSONArray(result);
   for (int i = 0; i < ja.length(); i++) {

     JSONObject jo = ja.getJSONObject(i);

     venue = venue
      .concat("\n Match id:" + jo.getString("match_id")
        + "\n pool_name :" + jo.getString("pool_name")
        + "\n team1_name :"
        + jo.getString("team1_name")
        + "\n team2_name :"
        + jo.getString("team2_name")
        + "\n match_date :"
        + jo.getString("match_date") + "\n venue :"
        + jo.getString("match_venue") + "\n    ");
    Log.d("msg", jo.toString());
    System.out.println(venue);
    tv.setText(venue);
   }

    reader.close();
   Toast.makeText(getBaseContext(), "Done reading SD 'mysdfile.txt'",
     Toast.LENGTH_SHORT).show();
  } catch (Exception e) {
   Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT)
     .show();
   Log.d("error", e.getMessage());
  }
 }

the overall code:




package com.example.test;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
 TextView tv;
 final File dir = new File(Environment.getExternalStorageDirectory()
   .getPath() + "/Android/data/" + getPackageName() + "/");
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  tv = (TextView) findViewById(R.id.textView1);
  System.out.println("Tessting!");
  writeFile();
  readFile();

 }

 public void writeFile() {

  try {
   

   try {
    if (!dir.exists()) {

     dir.mkdirs();

     Toast.makeText(getBaseContext(), "Directory created",
       Toast.LENGTH_SHORT).show();
     final String filename = "test.txt";

     File file = new File(dir, filename);
     file.createNewFile();
     FileOutputStream fOut = new FileOutputStream(file);
     OutputStreamWriter myOutWriter = new OutputStreamWriter(
       fOut);
     myOutWriter.write(filename);
     myOutWriter.close();
     fOut.close();
    }
   } catch (Exception e) {
    e.printStackTrace();
   }

   Toast.makeText(getBaseContext(), "Done writing SD 'mysdfile.txt'",
     Toast.LENGTH_SHORT).show();
  } catch (Exception e) {
   Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT)
     .show();
  }

 }

 public void readFile() {

  FileInputStream fIn;
  String result = null, venue = " ";
  try {
   
   File myFile = new File("/sdcard/Android/data/com.example.test/test.txt");
   
   fIn = new FileInputStream(myFile);
   BufferedReader reader = new BufferedReader(new InputStreamReader(
     fIn, "UTF-8"), 8);
   StringBuilder sb = new StringBuilder();
   String line = null;
   while ((line = reader.readLine()) != null) {
    sb.append(line + "\n");
   }
   fIn.close();
   result = sb.toString();
   Log.d("result", result);
   JSONArray ja = new JSONArray(result);
   for (int i = 0; i < ja.length(); i++) {

    JSONObject jo = ja.getJSONObject(i);

    venue = venue
      .concat("\n Match id:" + jo.getString("match_id")
        + "\n pool_name :" + jo.getString("pool_name")
        + "\n team1_name :"
        + jo.getString("team1_name")
        + "\n team2_name :"
        + jo.getString("team2_name")
        + "\n match_date :"
        + jo.getString("match_date") + "\n venue :"
        + jo.getString("match_venue") + "\n    ");
    Log.d("msg", jo.toString());
    System.out.println(venue);
    tv.setText(venue);
   }

   reader.close();
   Toast.makeText(getBaseContext(), "Done reading SD 'mysdfile.txt'",
     Toast.LENGTH_SHORT).show();
  } catch (Exception e) {
   Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT)
     .show();
   Log.d("error", e.getMessage());
  }
 }

}
}
}





Comments

Popular posts from this blog

Adding Markers in Google Map and Focusing Camera when map loaded

Creating Simple Horizontal graph in android using android Weight property without any External Libraries