Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does InputStream.available() do in Java?

What does InputStream.available() do in Java? I read the documentation, but I still cannot make it out.

The doc says:

Returns the number of bytes that can be read (or skipped over) from this input stream without blocking by the next caller of a method for this input stream. The next caller might be the same thread or or another thread.

The available method for class InputStream always returns 0.

What do they mean by blocking? Does it just mean a synchronized call?

And most of all, what is the purpose of the available() method?

like image 993
Albus Dumbledore Avatar asked Sep 12 '10 15:09

Albus Dumbledore


People also ask

What does InputStream available do?

The available() method of FileInputStream class is used to return the estimated number of remaining bytes that can be read from the input stream without blocking. This method returns the number of bytes remaining to read from the file. When a file is completely read, this function returns zero.

What is available () in java?

The java. io. FileInputStream. available() method returns number of remaining bytes that can be read from this input stream without blocking by the next method call for this input stream.

How does InputStream read () method work?

read() method reads the next byte of the data from the the input stream and returns int in the range of 0 to 255. If no byte is available because the end of the stream has been reached, the returned value is -1.

What is the return type of available method of InputStream class?

The available method for class InputStream always returns 0 . This method should be overridden by subclasses. Returns: an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking or 0 when it reaches the end of the input stream.


1 Answers

In InputStreams, read() calls are said to be "blocking" method calls. That means that if no data is available at the time of the method call, the method will wait for data to be made available.

The available() method tells you how many bytes can be read until the read() call will block the execution flow of your program. On most of the input streams, all call to read() are blocking, that's why available returns 0 by default.

However, on some streams (such as BufferedInputStream, that have an internal buffer), some bytes are read and kept in memory, so you can read them without blocking the program flow. In this case, the available() method tells you how many bytes are kept in the buffer.

like image 70
Vivien Barousse Avatar answered Sep 30 '22 02:09

Vivien Barousse