问题
Is there a way to make BufferedReader.readLine()
not hang?
I'm creating a server that:
- Checks if the client has delivered any input.
- If not, it executes other code and eventually loops back to checking the client for input.
How can I check if the client has delivered any input without running readLine()
? If I run readLine()
, the thread will hang until input is delivered?
回答1:
You can use BufferedReader.ready()
, like this:
BufferedReader b = new BufferedReader(); //Initialize your BufferedReader in the way you have been doing before, not like this.
if(b.ready()){
String input = b.readLine();
}
ready()
will return true
if the source of the input has not put anything into the stream that has not been read.
Edit: Just a note, ready will return true
whenever even only one character is present. You can use read()
to check if there is a line feed or carriage return, and those would indicate an end of line.
For more info: http://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html#ready()
来源:https://stackoverflow.com/questions/15510820/how-can-you-make-bufferedreader-readline-not-hang