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.
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 an int
to represent the lookahead and a boolean
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.