14

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.

tshepang
  • 12,111
  • 21
  • 91
  • 136
George N
  • 151
  • 1
  • 1
  • 4

5 Answers5

14

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();
}
Matt
  • 688
  • 5
  • 12
Labeeb Panampullan
  • 34,521
  • 28
  • 94
  • 112
7
//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());
    }

}
Hiren Patel
  • 52,124
  • 21
  • 173
  • 151
3

To get the words from the file from raw folder try with the following approach

Read the data from raw folder using getResources().openRawResource(R.raw.song);
Then get the inputstream data in a byte array split the data with space.

Use the following code

InputStream is =getResources().openRawResource(R.raw.song);
            BufferedInputStream bis = new BufferedInputStream(is);

            ByteArrayBuffer baf = new ByteArrayBuffer(50);

            int current = 0;

            while ((current = bis.read()) != -1) {

                baf.append((byte) current);

            }

            byte[] myData = baf.toByteArray();
            String dataInString = new String(myData);
            String[] words = dataInString.split(" ");

Thanks Deepak

Sunil Kumar Sahoo
  • 53,011
  • 55
  • 178
  • 243
  • 2
    -1 for reading byte by byte ... i've seen this pattern: `while ((current = bis.read()) != -1) { ...` in many response ... guy who posted(not you) it first should be shooted – Selvin Jan 24 '12 at 12:33
3

The simplest is to use a Scanner.

Scanner s = new Scanner(getResources().openRawResource(R.raw.text_file));

try {
    while (s.hasNext()) {
        String word = s.next();
        // ....
    }
} finally {
    s.close();
}

The default delimiter is whitespace (including space). If you want it to only trigger on space use s.useDelimiter(" "); after creating it.

dacwe
  • 43,066
  • 12
  • 116
  • 140
  • Using this code with a text file that has only a few words, works just fine. But when I use the file that has about 100,000 words the emulator stops responding. Why do you think? – George N Jun 22 '11 at 16:34
  • Well... That's a down side of this solution as the `Scanner` will create new strings for every call to `next()` and that could be expensive. But that's really **another problem and should be asked in a new question** (*I would use @Sunil Kumar Sahoo solution if you have files that big since the `split(..)` method doesn't create new strings but reuses the underlying string*). – dacwe Jun 23 '11 at 08:49
2

I had this same question and while the above answers are probably correct I was unable to get them to work successfully. This was almost certainly operator error and ignorance on my part - but just in case someone wants to see how I - a n00b - finally did it, here is my solution:

// this is just the click handler for a button...
public void loadStatesHandler(View v) {
    try {  
        String states = getStringFromRaw(this);
        readOutput.setText(states);
    } 
    catch(Throwable t) {
        t.printStackTrace();
    }
}

private String getStringFromRaw(Context c) throws IOException {
        Resources r = c.getResources();
        InputStream is = r.openRawResource(R.raw.states);
        String statesText = convertStreamToString(is);
        is.close();
        return statesText;
}

private String convertStreamToString(InputStream is) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    int i = is.read();
    while (i != -1) {
        baos.write(i);
        i = is.read();
    }
    return baos.toString();
}

I'm not exactly sure why this worked for me when the above didn't as it doesn't seem fundamentally different - but as I said - it was probably operator error on my part.

Bennett Von Bennett
  • 307
  • 1
  • 6
  • 17