How can I read a text file in Android?

JavaAndroidExceptionInputstream

Java Problem Overview


I want to read the text from a text file. In the code below, an exception occurs (that means it goes to the catch block). I put the text file in the application folder. Where should I put this text file (mani.txt) in order to read it correctly?

    try
	{
		InputStream instream = openFileInput("E:\\test\\src\\com\\test\\mani.txt"); 
		if (instream != null)
		{
		    InputStreamReader inputreader = new InputStreamReader(instream); 
		    BufferedReader buffreader = new BufferedReader(inputreader); 
		    String line,line1 = "";
		    try
		    {
		    	while ((line = buffreader.readLine()) != null)
		    		line1+=line;
		    }catch (Exception e) 
		    {
		        e.printStackTrace();
		    }
		 }
	}
	catch (Exception e) 
	{
		String error="";
		error=e.getMessage();
    }

Java Solutions


Solution 1 - Java

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 file
File file = new File(sdcard,"file.txt");

//Read text from file
StringBuilder 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 id
TextView tv = (TextView)findViewById(R.id.text_view);

//Set the text
tv.setText(text.toString());

following links can also help you :

https://stackoverflow.com/questions/2902689/how-can-i-read-a-text-file-from-the-sd-card-in-android

https://stackoverflow.com/questions/3344551/how-to-read-text-file-in-android

https://stackoverflow.com/questions/4087674/android-read-text-raw-resource-file

Solution 2 - Java

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

Good example of reading text file from res/raw folder

Solution 3 - Java

Solution 4 - Java

Try this code

public static String pathRoot = "/sdcard/system/temp/";
public static String readFromFile(Context contect, String nameFile) {
	String aBuffer = "";
	try {
		File myFile = new File(pathRoot + nameFile);
		FileInputStream fIn = new FileInputStream(myFile);
		BufferedReader myReader = new BufferedReader(new InputStreamReader(fIn));
		String aDataRow = "";
		while ((aDataRow = myReader.readLine()) != null) {
			aBuffer += aDataRow;
		}
		myReader.close();
	} catch (FileNotFoundException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	}
	return aBuffer;
}

Solution 5 - Java

First you store your text file in to raw folder.

private void loadWords() throws IOException {
    Log.d(TAG, "Loading words...");
	final Resources resources = mHelperContext.getResources();
	InputStream inputStream = resources.openRawResource(R.raw.definitions);
    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

    try {
        String line;
	    while ((line = reader.readLine()) != null) {
	        String[] strings = TextUtils.split(line, "-");
	        if (strings.length < 2)
                continue;
	        long id = addWord(strings[0].trim(), strings[1].trim());
	        if (id < 0) {
	            Log.e(TAG, "unable to add word: " + strings[0].trim());
	        }
	    }
	} finally {
	    reader.close();
	}
	Log.d(TAG, "DONE loading words.");
}

Solution 6 - Java

Try this

try {
		reader = new BufferedReader(new InputStreamReader(in,"UTF-8"));
	} catch (UnsupportedEncodingException e1) {
		// TODO Auto-generated catch block
		e1.printStackTrace();
	}
      String line="";
      String s ="";
   try 
   {
	   line = reader.readLine();
   } 
   catch (IOException e) 
   {
	   e.printStackTrace();
   }
      while (line != null) 
      {
       s = s + line;
       s =s+"\n";
       try 
       {
    	   line = reader.readLine();
       } 
       catch (IOException e) 
       {
    	   e.printStackTrace();
       }
    }
    tv.setText(""+s);
  }

Solution 7 - Java

Shortest form for small text files (in Kotlin):

val reader = FileReader(path)
val txt = reader.readText()
reader.close()

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1635224View Question on Stackoverflow
Solution 1 - JavaShrutiView Answer on Stackoverflow
Solution 2 - JavaSandip Armal PatilView Answer on Stackoverflow
Solution 3 - JavaPriyank PatelView Answer on Stackoverflow
Solution 4 - JavaHuynhHanView Answer on Stackoverflow
Solution 5 - JavaRamView Answer on Stackoverflow
Solution 6 - JavaMuhammad Usman GhaniView Answer on Stackoverflow
Solution 7 - JavaEnekoView Answer on Stackoverflow