什么时候FileInputStream.read()阻止? [英] when does FileInputStream.read() block?

查看:85
本文介绍了什么时候FileInputStream.read()阻止?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题类似于以下两个问题.

The question is similar to the following two questions.

  • 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.

"无可用输入"是什么意思?

谢谢.

推荐答案

您的问题的答案可以在

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()阻止?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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