Reading a simple text file

AndroidText FilesJava Io

Android Problem Overview


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.

Android Solutions


Solution 1 - Android

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

Solution 2 - Android

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

Solution 3 - Android

This is how I do it:

public static String readFromAssets(Context context, String filename) throws IOException {
	BufferedReader reader = new BufferedReader(new InputStreamReader(context.getAssets().open(filename)));

	// do reading, usually loop until end of file reading  
	StringBuilder sb = new StringBuilder();
	String mLine = reader.readLine();
	while (mLine != null) {
		sb.append(mLine); // process line
		mLine = reader.readLine();
	}
	reader.close();
	return sb.toString();
}

use it as follows:

readFromAssets(context,"test.txt")

Solution 4 - Android

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.

Solution 5 - Android

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

Solution 6 - Android

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

Solution 7 - Android

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

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
QuestionDalvinder SinghView Question on Stackoverflow
Solution 1 - AndroidshihpengView Answer on Stackoverflow
Solution 2 - AndroidJazzView Answer on Stackoverflow
Solution 3 - AndroidAsaf PinhassiView Answer on Stackoverflow
Solution 4 - AndroidWroclaiView Answer on Stackoverflow
Solution 5 - AndroidJxDarkAngel from Mexico CityView Answer on Stackoverflow
Solution 6 - Androidyubaraj poudelView Answer on Stackoverflow
Solution 7 - AndroiducMediaView Answer on Stackoverflow