How can I read a text file in Android?
Try this :
I assume your text file is on sd card
//Find the directory for the SD Card using the API//*Don't* hardcode "/sdcard"File sdcard = Environment.getExternalStorageDirectory();//Get the text fileFile file = new File(sdcard,"file.txt");//Read text from fileStringBuilder text = new StringBuilder();try { BufferedReader br = new BufferedReader(new FileReader(file)); String line; while ((line = br.readLine()) != null) { text.append(line); text.append('\n'); } br.close();}catch (IOException e) { //You'll need to add proper error handling here}//Find the view by its idTextView tv = (TextView)findViewById(R.id.text_view);//Set the texttv.setText(text.toString());
following links can also help you :
How can I read a text file from the SD card in Android?
If you want to read file from sd card. Then following code might be helpful for you.
StringBuilder text = new StringBuilder(); try { File sdcard = Environment.getExternalStorageDirectory(); File file = new File(sdcard,"testFile.txt"); BufferedReader br = new BufferedReader(new FileReader(file)); String line; while ((line = br.readLine()) != null) { text.append(line); Log.i("Test", "text : "+text+" : end"); text.append('\n'); } } catch (IOException e) { e.printStackTrace(); } finally{ br.close(); } TextView tv = (TextView)findViewById(R.id.amount); tv.setText(text.toString()); ////Set the text to text view. } }
If you wan to read file from asset folder then
AssetManager am = context.getAssets();InputStream is = am.open("test.txt");
Or If you wan to read this file from res/raw
foldery, where the file will be indexed and is accessible by an id in the R file:
InputStream is = getResources().openRawResource(R.raw.test);
Put your text file in Asset Folder...& read file form that folder...
see below reference links...
http://www.technotalkative.com/android-read-file-from-assets/
http://sree.cc/google/reading-text-file-from-assets-folder-in-android
hope it will help...