-4

How to read .txt file from drawable or any other folder in android using FileInputStream?

I have a .txt file in my drawable folder. How can i read the file and set it in Textview?

Ankush Kapoor
  • 282
  • 1
  • 3
  • 16

2 Answers2

3

Try This with help of this u can read file from drawable folder

        String data = "";
        StringBuffer sbuffer = new StringBuffer();
        InputStream is = this.getResources().openRawResource(+
                R.drawable.filetoread);
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        if (is != null) {
            try {
                while ((data = reader.readLine()) != null) {
                    sbuffer.append(data + "\n");
                }
                is.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
         data = sbuffer.toString(),
        }
Vanraj Ghed
  • 1,231
  • 11
  • 23
  • Despite text files shouldn't be in the drawable folder as stated by @Abdul Fatir, this is useful to copy, for example, gif files that cannot be copied as a bitmap. – Juan Giorello Feb 07 '17 at 14:13
1

Why would you want to keep your .txt in the drawable/ folder? It's better that you keep it in the assets folder instead and read it as described in this SO.

BufferedReader reader = null;
try {
    reader = new BufferedReader(
        new InputStreamReader(getAssets().open("filename.txt")));

    // do reading, usually loop until end of file reading  
    String mLine;
    while ((mLine = reader.readLine()) != null) {
       //process line
       ...
    }
} catch (IOException e) {
    //log the exception
} finally {
    if (reader != null) {
         try {
             reader.close();
         } catch (IOException e) {
             //log the exception
         }
    }
}
Community
  • 1
  • 1
Abdul Fatir
  • 5,903
  • 5
  • 27
  • 56