130

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();
    }
Community
  • 1
  • 1
user1635224
  • 1,515
  • 2
  • 14
  • 15

7 Answers7

265

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 :

How can I read a text file from the SD card in Android?

How to read text file in Android?

Android read text raw resource file

A-Sharabiani
  • 15,608
  • 15
  • 99
  • 122
Shruti
  • 8,785
  • 12
  • 54
  • 93
  • 3
    your link would be helps me to achieve – user1635224 Sep 14 '12 at 09:59
  • 11
    The BufferedReader need to close at the end! – RainClick Dec 01 '13 at 05:34
  • 2
    If you have one empty row in your txt doc, this parser will stop working! The solution is to admit having this empty rows: `while ((line = br.readLine()) != null) { if(line.length() > 0) { //do your stuff } }` – Choletski Oct 23 '15 at 08:03
  • @Shruti how to add the file into SD card – Tharindu Dhanushka Mar 01 '16 at 07:25
  • @Choletski, why do you say it will stop working? If there is a blank line, the blank line will be appended to the text StringBuilder. What's the problem? – LarsH Apr 19 '16 at 21:29
  • @LarsH I was trying this method, it's working good but if the file have empty lines parser don't pass them but just stops like end of file. – Choletski Apr 20 '16 at 07:03
  • @Choletski: It seems the problem you're seeing must be something different. You haven't changed the `while ()` condition, so the only thing to stop the loop would be an exception. How could `text.append(line)` throw an exception, when `line` is a zero-length string? – LarsH Apr 21 '16 at 13:46
  • `You'll need to add proper error handling here` must be the most frequent sentence in any Java tutorial. – boot4life May 24 '17 at 15:55
  • `FileReader` has the major part in this – Sachin K Pissay Jun 24 '20 at 05:38
31

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

Sandip Armal Patil
  • 6,285
  • 20
  • 86
  • 152
8

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

Reading a simple text file

hope it will help...

Community
  • 1
  • 1
Priyank Patel
  • 11,919
  • 8
  • 62
  • 82
5

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;
}
Massimiliano Kraus
  • 3,433
  • 5
  • 24
  • 45
HuynhHan
  • 355
  • 1
  • 4
  • 11
3

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.");
}
Ole V.V.
  • 76,217
  • 14
  • 120
  • 142
Ram
  • 1,717
  • 3
  • 18
  • 28
1

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);
  }
Muhammad Usman Ghani
  • 1,281
  • 13
  • 19
1

Shortest form for small text files (in Kotlin):

val reader = FileReader(path)
val txt = reader.readText()
reader.close()
Eneko
  • 1,195
  • 1
  • 11
  • 19