java 如何让 BufferedReader.readLine() 不挂起?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15510820/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 19:51:33  来源:igfitidea点击:

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

javabufferedreader

提问by Cin316

Is there a way to make BufferedReader.readLine()not hang?

有没有办法让BufferedReader.readLine()不挂?

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?

如何在不运行的情况下检查客户端是否提供了任何输入readLine()?如果我运行readLine(),线程将挂起直到输入被传送?

回答by Cin316

You can use BufferedReader.ready(), like this:

你可以使用BufferedReader.ready(),像这样:

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 trueif the source of the input has not put anything into the stream that has not been read.

ready()true如果输入源没有将任何内容放入尚未读取的流中,则将返回。

Edit: Just a note, ready will return truewhenever 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.

编辑:只是一个注释,true即使只有一个字符存在,ready 也会返回。您可以read()用来检查是否有换行符或回车符,这些表示行尾。

For more info: http://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html#ready()

更多信息:http: //docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html#ready()