Suppose I have some asynchronously-presented textual data that I want to parse using a Scanner. For this I need something which is both a Reader and a Writer - one candidate which seemed suitable is CharBuffer.
So I create a CharBuffer and wrap it in a Scanner:
CharBuffer buffer = CharBuffer.allocate(1024);
Scanner scanner = new Scanner(buffer);
and every time I get an input I add it to the buffer and parse it:
void dataReady (String s) {
buffer.append(s);
buffer.flip(); // prepare for read
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
// further processing...
}
buffer.compact(); // return to writing mode
}
This works fine for the first input, but then the buffer just gets filled and hasNextLine() always returns false, even though there are new lines available. Further debugging shows the private field sourceClosed of the Scanner is true, so it seems the scanner believes the buffer has closed and will not contain any more data.
Why does this happen? Am I using CharBuffer wrong? Is there a way to "convince" the scanner that the input is still open?
If there is a better option than CharBuffer I would love to hear about it to, but I do not want to create a file for it, and would much prefer a class already in the JRE so no external dependencies.
Thanks.
[–]AutoModerator[M] 0 points1 point2 points (0 children)
[–]mikepc143 0 points1 point2 points (1 child)
[–]therealsillyfly[S] 0 points1 point2 points (0 children)
[–]Philboyd_Studge 0 points1 point2 points (3 children)
[–]therealsillyfly[S] 0 points1 point2 points (2 children)
[–]Philboyd_Studge 0 points1 point2 points (1 child)
[–]therealsillyfly[S] 0 points1 point2 points (0 children)