Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

when does FileInputStream.read() block?

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.

like image 513
liam xu Avatar asked Mar 05 '13 08:03

liam xu


People also ask

What does the read () method of FileInputStream return?

The read() method of a FileInputStream returns an int which contains the byte value of the byte read. If the read() method returns -1, there is no more data to read in the stream, and it can be closed. That is, -1 as int value, not -1 as byte value.

Does FileInputStream need to be closed?

close() method. After any operation to the file, we have to close that file.

What is FileInputStream read in java?

The read() method of InputStream class reads a byte of data from the input stream. The next byte of data is returned, or -1 if the end of the file is reached and throws an exception if an I/O error occurs.

Is InputStream read blocking?

According to the java api, the InputStream. read() is described as: If no byte is available because the end of the stream has been reached, the value -1 is returned. This method blocks until input data is available, the end of the stream is detected, or an exception is thrown.


1 Answers

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,

like image 111
Anders R. Bystrup Avatar answered Sep 20 '22 22:09

Anders R. Bystrup