I'm writing a program that takes a Reader and parses input from that reader. I cannot use a BufferedReader, but I would like to implement a peek method that looks at the current char in the reader, without actually calling read() on that character. Is there an easier/better way to do this than converting it to a character array or a string and looking at the character? I would love to use the mark() method but unfortunately that only works on a buffered reader.
-
Why not BufferedReader? The reason for not using one may affect what, if any, solutions are available. – Patricia Shanahan Sep 20 '13 at 03:29
-
What about `PushbackInputStream`? – Mac Sep 20 '13 at 03:30
-
I'm writing this to a spec that dictates that we cannot use buffered readers. doesn't PushbackInputStream also require the use of a buffered reader? – user1601687 Sep 20 '13 at 03:33
2 Answers
The natural solution is to use PushBackReader
which provides unread
methods that can be used to implement peek
. (You can work out the details!)
But it is not entirely clear if this is allowed. It depends whether you are forbidden from using BufferedReader
or "a buffered Reader
". In the latter case, PushBackReader
is arguably a buffered Reader
.
If you have to implement this without using an existing buffered Reader
class, then how you should approach this depends on how much lookahead is needed:
If you need just one character lookahead (e.g. just
peek
) then you can implement this using anint
to represent the lookahead and aboolean
to say if it is currently valid.If you need multiple characters lookahead, you need an array (or list), and so on.
For the record, the mark()
and reset()
methods are actually in the Reader
API. The problem is that not all Reader
classes are able to implement these methods ... due to limitations of the underlying streams ... at the operating system level.

- 698,415
- 94
- 811
- 1,216
-
The spec is slightly ambiguous and states that the reader cannot be buffered. In this case I think that a pushback reader might be applicable because the reader itself isn't buffered, but contains a one character pushback buffer. It also does not support the mark operation, which is explicitly forbidden. – user1601687 Sep 20 '13 at 05:17
-
@user1601687 - interpreting your spec is really between you and whoever wrote it. I'm guessing it is your lecturer. But in that case, you would probably be better off considering what he/she intends you to do. And I'd surmise that he/she *intends* you to implement all of the peek / pushback code yourself ... as a programming exercise. I'm pretty sure they *don't* intend you to use `PushBackReader` ... and if you use it, you risk getting down-marked. – Stephen C Sep 20 '13 at 05:47
You can write your own class with peek method based on java.io.PushBackReader.

- 133,369
- 30
- 199
- 275