Translate

Sunday, April 27, 2014

Reading from a file in Android

There are couple ways to read from a file in android. The file can be included as part of the Android Project in to the res directory Or the file can also be read from SD Card or internal storage. I will share couple ways to read the content of a file.

Method 1: Reading from res directory
Lets say we have a file called test.txt. The first thing we need to do is create a new folder called raw within the res directory and store the file there. So out file location will look like this

res/raw/test.txt

The following code snippet will read the content of this file into a String.
 
InputStream inputStream = this.getResources().openRawResource(
    R.raw.test);
  ByteArrayOutputStream bos = new ByteArrayOutputStream();
  
 
   int i = 0;
   try {
    while((i = inputStream.read())!=-1) {
     bos.write(i);
    }
    bos.close();
    inputStream.close();
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  
  String content = bos.toString();
  Log.i("File Content is", content);



Method 2: Reading from External Storage/SD Card
say we have a file called test.txt in the root of sdcard. The following code snippet will read the file into a String object.
 
  File file = new File(Environment.getExternalStorageDirectory() + "/test.txt");
  try {
   FileReader fr = new FileReader(file);
   BufferedReader br = new BufferedReader(fr);
   StringBuffer sb = new StringBuffer();
   String line = "";
   while((line=br.readLine())!=null) {
    sb.append(line);
   }
   String content = sb.toString();
   Log.i("File Content is", content);
   br.close();
   fr.close();
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }

This method requires Read External Storage permission declared in the manifest file
 
android.permission.READ_EXTERNAL_STORAGE


Let me know if you have any question on the comments...