什么时候FileInputStream.read()阻止?

编程入门 行业动态 更新时间:2024-10-12 12:32:53
本文介绍了什么时候FileInputStream.read()阻止?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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()阻止?

本文发布于:2023-11-25 15:06:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1630226.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:什么时候   FileInputStream   read

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!