问题类似于以下两个问题.
The question is similar to the following two questions.
- Java InputStream阻止读取
- 为什么FileInputStream read()没有被阻止?
- Java InputStream blocking read
- Why is the FileInputStream read() not blocking?
但是我仍然不能完全理解它.
But I still cannot fully understand it.
到目前为止,由于空文件"test.txt",我认为以下代码中的 read()方法将被阻止.
So far I think the read() method in following code will block due to the empty file 'test.txt'.
FileInputStream fis = new FileInputStream("c:/test.txt"); System.out.println(fis.read()); System.out.println("to the end");实际上它会打印-1,我想知道为什么.
Actually it will print -1, I want to know why.
Javadoc说如果尚无可用输入,则此方法会阻塞.
The javadoc says This method blocks if no input is yet available.
"无可用输入"是什么意思?
谢谢.
推荐答案您的问题的答案可以在用于.read()的JavaDoc :
The answer to your question can be found in the JavaDoc for .read():
如果没有可用的输入,此方法将阻塞.
This method blocks if no input is yet available.
和
返回:下一个数据字节;如果到达文件末尾,则返回-1.
Returns: the next byte of data, or -1 if the end of the file is reached.
因此,一个空文件将立即为您提供-1(而不是read()阻止)
So, an empty file will get you an immediate -1 (instead of read() blocking) as
- 有 个输入可用,因为该文件存在
- ...但是它是空的,所以立即生效.
- there is input available, since the file exists
- ...but it is empty, so immediate EOF.
...尚无输入... 情况可能会发生,例如当一个是从一个命名管道而不是一个普通文件读取时,而管道的另一端还没有写任何东西.
The ...No input is yet available... situation could occur eg. when one was to read from a named pipe instead of a plain file, and the other side of the pipe hasn't written anything yet.
干杯
更多推荐
什么时候FileInputStream.read()阻止?
发布评论