hasNext() - when does it block and why?

狂风中的少年 提交于 2019-11-27 02:11:01
Haini

There is a difference between testing via Console or via TextFile. If I read from Console the program expects a Stream and it will wait for further Input.

When testing via Input from Textfile (still with System.in for the Scanner, using Java Program ) the hasNext() will return false at the end of the file as no further Input can be done.

I can't really find documentation (in https://docs.oracle.com/javase/9/docs/api/java/util/Scanner.html#hasNext--) on this Topic. So if anyone finds a proper and technical correct answer I would be very greatfull.

I'm not sure , but the following is my own experience :
when the Scanner object is fed with a file , it will not be blocking !
By the term "fed with a file " I mean that the scanner is constructed like this :
Scanner scanner = new Scanner("myFile.txt");

But if the scanner is constructed using the getInputStream()method of a Socket object , like this :

input = socket.getInputStream();
Scanner scanner = new Scanner(input);

the scanner will be blocking !

If you have nothing else to do while waiting for user input, then it's fine to be blocked at that call until the next input arrives.

If you do want to run other code while waiting for input, spawn a new thread and call hasNext and other blocking scanner methods from there.

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