How can you make BufferedReader.readLine() not hang?

五迷三道 提交于 2020-01-01 11:26:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!