Is there a way to check if in BufferedReader
object is something to read? Something like C++ cin.peek()
. Thanks.
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
You can try the "boolean ready()" method. From the Java 6 API doc: "A buffered character stream is ready if the buffer is not empty, or if the underlying character stream is ready."
The answer from pgmura (relying on the ready() method) is simple and works. But bear in mind that it's because Sun's implementation of the method; which does not really agree with the documentation. I would not rely on that, if this behaviour is critical. See here http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4090471 I'd rather go with the PushbackReader option.
The normal idiom is to check in a loop if
BufferedReader#readLine()
doesn't returnnull
. If end of stream is reached (e.g. end of file, socket closed, etc), then it returnsnull
.E.g.
If you don't want to read in lines (which is by the way the major reason a
BufferedReader
is been chosen), then useBufferedReader#ready()
instead:You can use a PushbackReader. Using that you can read a character, then unread it. This essentially allows you to push it back.
The following code will look at the first byte in the Stream. Should act as a peek for you.