Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I peek on a BufferedReader?

Tags:

Is there a way to check if in BufferedReader object is something to read? Something like C++ cin.peek(). Thanks.

like image 330
There is nothing we can do Avatar asked Mar 25 '10 17:03

There is nothing we can do


People also ask

How do I read BufferedReader?

The read() method of BufferedReader class in Java is used to read a single character from the given buffered reader. This read() method reads one character at a time from the buffered stream and return it as an integer value. Overrides: It overrides the read() method of Reader class.

Can BufferedReader read bytes?

It will read n bytes or chars data and store into a char array instead of reading again and again from i/o. Remember every read operation, is costlier and will have impact on performance.

What happens if you don't close a BufferedReader?

Closes this stream and releases any system resources associated with it. If the stream is already closed then invoking this method has no effect. So, if you don't close(), system resources may be still associated with the reader which may cause memory leak.

Do you need to close a BufferedReader?

When you are finished reading characters from the BufferedReader you should remember to close it. Closing a BufferedReader will also close the Reader instance from which the BufferedReader is reading.


2 Answers

You can use a PushbackReader. Using that you can read a character, then unread it. This essentially allows you to push it back.

PushbackReader pr = new PushbackReader(reader); char c = (char)pr.read(); // do something to look at c pr.unread((int)c); //pushes the character back into the buffer 
like image 114
Gavin H Avatar answered Oct 10 '22 13:10

Gavin H


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."

BufferedReader r = new BufferedReader(reader); if(r.ready()) {    r.read(); } 
like image 36
pgmura Avatar answered Oct 10 '22 14:10

pgmura