Search code examples
androidfilecpu-wordbufferedreader

How to read word by word from file?


Could anybody post here some code how can I read word by word from file? I only know how to read line by line from file using BufferedReader. I'd like if anybody posted it with BufferedReader.

I solved it with this code:

    StringBuilder word = new StringBuilder();
                int i=0;
                Scanner input = new Scanner(new InputStreamReader(a.getInputStream()));
                while(input.hasNext()) {
                    i++;
                    if(i==prefNamePosition){
                        word.append(prefName);
                        word.append(" ");
                        input.next();
                    }
                    else{
                        word.append(input.hasNext());
                        word.append(" ");
                    }
                }

Solution

  • If you're trying to replace the nth token with a special value, try this:

    while (input.hasNext()) {
        String currentWord = input.next();
        if(++i == prefNamePosition) {
            currentWord = prefName;
        }
        word.append(currentWord);
        word.append(" ");
    }