How to read word by word from file?

喜你入骨 提交于 2020-01-03 05:33:32

问题


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(" ");
                    }
                }

回答1:


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(" ");
}



回答2:


There's no good way other than to read() and get a character at a time until you get a space or whatever criteria you want for determining what a "word" is.




回答3:


Another way is to employ a tokenizer (e.g. in Java) and using the delimiter space character (i.e. ' '). Then just iterate through the tokens to read each word from your file.




回答4:


You can read lines and then use splits. There is no clear definition of word but if you want the ones separated by blank spaces you can do it.

You could also use regular expressions to do this.



来源:https://stackoverflow.com/questions/8825320/how-to-read-word-by-word-from-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!