Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading Android raw text file

I have a words.txt file which I have placed in my res/raw folder. The words in the file are separated by space. I'm having a hard time writing the Android/Java code to read the file word by word.

like image 207
George N Avatar asked Jun 21 '11 04:06

George N


People also ask

How do I view a raw text file?

Read raw (text) data with Excel. Use File > Open ; then, near the bottom of the dialog box, select Text Files from the Files of Type drop down list, the go to the folder where the data file is located and select it.

How do I read data on Android?

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()) !=


2 Answers

Read from res/raw folder to String

InputStream inputStream = getResources().openRawResource(R.raw.yourtextfile);
BufferedReader bufferedReader= new BufferedReader(new InputStreamReader(inputStream));
String eachline = bufferedReader.readLine();
while (eachline != null) {
    // `the words in the file are separated by space`, so to get each words 
    String[] words = eachline.split(" ");
    eachline = bufferedReader.readLine();
}
like image 54
Labeeb Panampullan Avatar answered Sep 28 '22 17:09

Labeeb Panampullan


//put your text file to raw folder, raw folder must be in resource folder. 

private TextView tv;
private Button btn;

    btn = (Button)findViewById(R.id.btn_json);
    tv = (TextView)findViewById(R.id.tv_text);

    btn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            SimpleText();


        }
    });

private void SimpleText(){

    try {


        InputStream is = this.getResources().openRawResource(R.raw.simpletext);
        byte[] buffer = new byte[is.available()];
        while (is.read(buffer) != -1);
        String jsontext = new String(buffer);



        tv.setText(jsontext);

    } catch (Exception e) {

        Log.e(TAG, ""+e.toString());
    }

}
like image 42
Hiren Patel Avatar answered Sep 28 '22 18:09

Hiren Patel