when does FileInputStream.read() block?

不打扰是莪最后的温柔 提交于 2021-02-18 12:10:58

问题


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.

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");

Actually it will print -1, I want to know why.

The javadoc says This method blocks if no input is yet available.

What does 'no input is available' mean?

thanks.


回答1:


The answer to your question can be found in the JavaDoc for .read():

This method blocks if no input is yet available.

and

Returns: the next byte of data, or -1 if the end of the file is reached.

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.

Cheers,




回答2:


FileInputStream can be used to read from things other than ordinary files. One obvious example is a named pipe: if you try to read from a pipe before the other side has written to it, the read operation will block.




回答3:


This maybe interperted as follows: FileInputStream.read invokes a native method, the native method makes the read system call and blocks waiting for OS to read the bytes from file into a buffer and returns when ready. That is, FileInputStream.read uses synchronous I/O to reads data from a file as opposed to non-blocking, asynchronous I/O.




回答4:


You can't interpret 'no input is available' as 'you are positioned at EOF and no more input will ever be available'. They are different conditions. The latter returns -1.

In general, all reads from files block until the data is available. The disk has to come around to the right point and the head has to seek to the right track. You also need to consider files that are on shared drives, or files that are named pipes, both of which involve network operations, which can also block.



来源:https://stackoverflow.com/questions/15218750/when-does-fileinputstream-read-block

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