简体   繁体   中英

when does FileInputStream.read() block?

The question is similar to the following two questions.

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.

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,

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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