118

I am trying to read a simple text file in my sample Android Application. I am using the below written code for reading the simple text file.

InputStream inputStream = openFileInput("test.txt");
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

My questions is : Where should I place this "test.txt" file in my project?. I have tried putting the file under "res/raw" and "asset" folder but I get the exception "FileNotFound" when first live of the code written above gets executed.

ggorlen
  • 44,755
  • 7
  • 76
  • 106
Dalvinder Singh
  • 2,129
  • 4
  • 21
  • 20

6 Answers6

183

Place your text file in the /assets directory under the Android project. Use AssetManager class to access it.

AssetManager am = context.getAssets();
InputStream is = am.open("test.txt");

Or you can also put the file in the /res/raw directory, where the file will be indexed and is accessible by an id in the R file:

InputStream is = context.getResources().openRawResource(R.raw.test);
Sebastian Hojas
  • 4,158
  • 2
  • 27
  • 38
shihpeng
  • 5,283
  • 6
  • 37
  • 63
  • 9
    Was wondering about the difference in performance between this two methods and a quick benchmark showed no appreciable differences. – Reuben L. Jun 02 '13 at 12:02
  • What is the size of text file used for benchmark testing and did you put images and other resources in your res folder that simulates to a real-time(commercial/free) android app? – Sree Rama Jun 07 '13 at 11:38
  • Shouldn't **is** be closed in a try/finally block? – saiyancoder Apr 24 '14 at 20:15
  • @R.L. Because one method is just another method's wrapper, the underlying is exactly the same implementation. – shihpeng Oct 22 '14 at 02:53
  • 2
    I do not have "asset" folder in my "hello world" app. Should I create manually ? – Kaushik Lele Dec 30 '14 at 12:25
  • How will I get context ? In my Java class for an activity – Kaushik Lele Dec 30 '14 at 12:45
  • @ReubenL. One of the difference is in /assets, the file cannot more than 1 Mb, meanwhile in /res/raw, the file can more than 1Mb. source: http://stackoverflow.com/questions/4430004/adding-a-big-text-file-to-assets-folder – Tutompita Jun 07 '15 at 21:19
  • 4
    Btw, the `/assets` dir has to be manually added as of Android Studio 1.2.2. It should go in `src/main`. – Jpaji Rajnish Jul 02 '15 at 17:21
  • 3
    For those like @KaushikLele, who are wondering how they can get context; it's easy. In an activity you can simply get it by using the "this" keyword or calling the "getCurrentContext()" method. – Alex Aug 16 '16 at 14:13
25

try this,

package example.txtRead;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.Vector;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class txtRead extends Activity {
    String labels="caption";
    String text="";
    String[] s;
    private Vector<String> wordss;
    int j=0;
    private StringTokenizer tokenizer;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        wordss = new Vector<String>();
        TextView helloTxt = (TextView)findViewById(R.id.hellotxt);
        helloTxt.setText(readTxt());
 }

    private String readTxt(){

     InputStream inputStream = getResources().openRawResource(R.raw.toc);
//     InputStream inputStream = getResources().openRawResource(R.raw.internals);
     System.out.println(inputStream);
     ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

     int i;
  try {
   i = inputStream.read();
   while (i != -1)
      {
       byteArrayOutputStream.write(i);
       i = inputStream.read();
      }
      inputStream.close();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }

     return byteArrayOutputStream.toString();
    }
}
7

Having a file in your assets folder requires you to use this piece of code in order to get files from the assets folder:

yourContext.getAssets().open("test.txt");

In this example, getAssets() returns an AssetManager instance and then you're free to use whatever method you want from the AssetManager API.

Wroclai
  • 26,835
  • 7
  • 76
  • 67
5

In Mono For Android....

try
{
    System.IO.Stream StrIn = this.Assets.Open("MyMessage.txt");
    string Content = string.Empty;
    using (System.IO.StreamReader StrRead = new System.IO.StreamReader(StrIn))
    {
      try
      {
            Content = StrRead.ReadToEnd();
            StrRead.Close();
      }  
      catch (Exception ex) { csFunciones.MostarMsg(this, ex.Message); }
      }
          StrIn.Close();
          StrIn = null;
}
catch (Exception ex) { csFunciones.MostarMsg(this, ex.Message); }
Vishal Yadav
  • 3,642
  • 3
  • 25
  • 42
3

To read the file saved in assets folder

public static String readFromFile(Context context, String file) {
        try {
            InputStream is = context.getAssets().open(file);
            int size = is.available();
            byte buffer[] = new byte[size];
            is.read(buffer);
            is.close();
            return new String(buffer);
        } catch (Exception e) {
            e.printStackTrace();
            return "" ;
        }
    }
yubaraj poudel
  • 3,821
  • 1
  • 31
  • 28
  • 1
    “is.available();” is not safe. Use AssetFileDescriptor fd = getAssets().openFd(fileName); int size = (int) fd.getLength(); fd.close(); – GBY Dec 01 '17 at 10:48
0

Here is a simple class that handles both raw and asset files :

public class ReadFromFile {

public static String raw(Context context, @RawRes int id) {
    InputStream is = context.getResources().openRawResource(id);
    int size = 0;
    try {
        size = is.available();
    } catch (IOException e) {
        e.printStackTrace();
        return "";
    }
    return readFile(size, is);
}

public static String asset(Context context, String fileName) {
    InputStream is = null;
    int size = 0;
    try {
        is = context.getAssets().open(fileName);
        AssetFileDescriptor fd = null;
        fd = context.getAssets().openFd(fileName);
        size = (int) fd.getLength();
        fd.close();
    } catch (IOException e) {
        e.printStackTrace();
        return "";
    }
    return readFile(size, is);
}


private static String readFile(int size, InputStream is) {
    try {
        byte buffer[] = new byte[size];
        is.read(buffer);
        is.close();
        return new String(buffer);
    } catch (Exception e) {
        e.printStackTrace();
        return "";
    }
}

}

For example :

ReadFromFile.raw(context, R.raw.textfile);

And for asset files :

ReadFromFile.asset(context, "file.txt");
ucMedia
  • 4,105
  • 4
  • 38
  • 46