Reputation: 2192
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(" ");
}
}
Upvotes: 0
Views: 2326
Reputation: 2983
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.
Upvotes: 0
Reputation: 17800
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(" ");
}
Upvotes: 0
Reputation: 228
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.
Upvotes: 0
Reputation: 1432
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.
Upvotes: 1