你怎么能让BufferedReader.readLine()不挂? [英] How can you make BufferedReader.readLine() not hang?

查看:104
本文介绍了你怎么能让BufferedReader.readLine()不挂?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我正在创建一个服务器:

I'm creating a server that:


  • 检查客户是否已提供任何输入。

  • 如果没有,则执行其他代码并最终循环回检查客户端输入。

如何在不运行 readLine()?如果我运行 readLine(),线程将挂起,直到输入被传递?

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?

推荐答案

您可以使用 BufferedReader.ready(),如下所示:

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()如果输入源没有将任何内容放入尚未读取的流中,则返回 true

ready() will return true if the source of the input has not put anything into the stream that has not been read.

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

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.

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

这篇关于你怎么能让BufferedReader.readLine()不挂?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆