BufferedReader, detecting if there is text to read

I start the stream and every time it starts, it must check if there is a new line to read from the BufferedReader , although it gets stuck waiting for the line to exist, thereby stopping all the code.

 if((inputLine = bufferedReader.readLine()) != null){ System.out.println(inputLine); JOptionPane.showMessageDialog(null, inputLine); } 

Is there a better way to check if the text in BufferedReader readable?

+4
source share
3 answers

No, there is no easy way to do this. BufferedReader has a ready call, but this only applies to read calls, not a readLine call. If you really need readLine , which is not guaranteed to be blocked, you must implement it yourself using read and independently support the char buffer.

+3
source

Why don't you check if he is ready to be the first? Just use bufferedReader.ready() .

Edit:

ready will not tell you if you have a line, it will just tell you that there is something to read. However, if you expect to get a string, this will work for you. The idea would be to first check if it is ready, and then read the line, so the thread will not hang there when there is absolutely nothing to read.

+1
source

The readLine method will be blocked if it cannot read the whole line (limited by the line termination character) or the end of the input is reached:

http://docs.oracle.com/javase/6/docs/api/java/io/BufferedReader.html#readLine ()

The thing you are describing is that the end of the input has not yet been reached, but the buffer does not have enough characters to make up a "string" (that is, a sequence of characters ending in a string terminator).

You need to go below the readLine level for this, possibly the Stream level itself. InputStream has a method called available() that will suit your needs.

0
source

All Articles