简体   繁体   English

Scanner.nextLine()何时阻止?

[英]When Does Scanner.nextLine() block?

I'm using a Scanner for my socket connection in a Client/Server program. 我在客户端/服务器程序中使用扫描仪进行套接字连接。

I want Scanner.next() to block so the Server thread can wait for something to read. 我希望Scanner.next()阻塞,以便服务器线程可以等待读取内容。

However, it sometimes gives me: 但是,它有时会给我:

java.util.NoSuchElementException: No line found
    at java.util.Scanner.nextLine(Scanner.java:1585)
    at cscie55.hw4.Server.serviceClient(Server.java:146)
    at cscie55.hw4.Server.main(Server.java:106)

The java documentation says that next() "sometimes" blocks, and it doesn't say whether nextLine() blocks. java文档说next()“有时”阻塞,并没有说明nextLine()是否阻塞。

Some code online wraps it in an if that tests for null, but I read that it never returns null. 一些代码在线将它包装在一个if测试null中,但我读到它永远不会返回null。 What should I do to get blocking IO working properly in my socket? 我应该怎么做才能阻止IO在我的套接字中正常工作?

Specifically, 特别,

When does Scanner.nextLine() block rather than throw NoSuchElementException? Scanner.nextLine()何时阻止而不是抛出NoSuchElementException?

The Scanner class will block whenever the InputStream used to construct it would block. 只要用于构造它的InputStream阻塞, Scanner类就会阻塞。 It will usually not block when reading from a file because the contents of it are readily available (ie, inputStream.available() > 0 ), they are on your machine after all. 从文件读取时通常不会阻塞,因为它的内容随时可用(即inputStream.available() > 0 ),它们毕竟在你的机器上。 However, if you construct a Scanner using an InputStream that may require waiting for data to arrive (eg, reading text from a remote client, waiting for a page to load so you can read its source, etc.) then Scanner#nextLine() will block because it needs to wait for enough information to build the next line to arrive. 但是,如果您使用可能需要等待数据到达的InputStream构建Scanner (例如,从远程客户端读取文本,等待页面加载以便您可以读取其来源等),则Scanner#nextLine()将阻止,因为它需要等待足够的信息来构建下一行到达。

It blocks if it's reading from a network and there is no data or no newline present in the input and it hasn't reached EOS. 它阻止它从网络读取并且输入中没有数据或没有换行符且它没有到达EOS。 You must be reading from a file. 您必须从文件中读取。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM