BufferedReader, detecting if there is text left to read

拟墨画扇 提交于 2019-11-30 05:28:07

问题


I'm running a thread and everytime it runs, It should be checking to see if there is a new line to read from the BufferedReader although, it gets stuck waiting for a line to exist, thus halting the entire code.

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

Is there a way to better check if there is text in a BufferedReader to be read?


回答1:


No, there's no easy way to do that. BufferedReader has a ready call, but that only applies to the read calls, not the readLine call. If you really want a readLine that's guaranteed not to block, you must implement it yourself using read and maintaining a char buffer yourself.




回答2:


Why don't you check if it's ready to be read first? Just use bufferedReader.ready().

Edit:

ready won't tell you if you have a line ready, it will just tell you that there is something to be read. However, if you are expecting to get a line then this will work for you. The idea would be, first check if it's ready, and then read the line, in this way the thread won't be hanging there when there is absolutely nothing to read.




回答3:


The readLine method will block unless it can read an entire line (delimited by a line-terminating character), or the end of input has been reached:

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

The case you're describing is that the end of input hasn't yet been reached, but there's not enough characters in the buffer to constitute a "line" (that is, a series of characters ended by a line terminator).

You will have to go lower than the readLine level for that, possibly to the Stream level itself. InputStream has a method called available(), which would answer your needs.



来源:https://stackoverflow.com/questions/13596138/bufferedreader-detecting-if-there-is-text-left-to-read

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