119

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.

6 Answers 6

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); 
Sign up to request clarification or add additional context in comments.

9 Comments

Was wondering about the difference in performance between this two methods and a quick benchmark showed no appreciable differences.
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?
I do not have "asset" folder in my "hello world" app. Should I create manually ?
Btw, the /assets dir has to be manually added as of Android Studio 1.2.2. It should go in src/main.
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.
|
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(); } } 

Comments

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.

Comments

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); } 

Comments

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 "" ; } } 

1 Comment

“is.available();” is not safe. Use AssetFileDescriptor fd = getAssets().openFd(fileName); int size = (int) fd.getLength(); fd.close();
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"); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.