The available() Method and Stream Availability
You'll learn how to check how many bytes can be read immediately from a stream without waiting, and why this number is only an estimate.
What Is available()?
The available() method is defined in InputStream and returns an int representing the number of bytes that can be read (or skipped over) from the stream without blocking. Blocking means your program would have to pause and wait—perhaps for more data to arrive over a network or for a disk read to complete.
Think of available() like checking how much water is already in the visible part of a pipe before you try to pour it out. You can see at least that much, but there might be more water further down the pipe that hasn't arrived yet.
Why It's an Estimate
The documentation explicitly states that available() returns an estimate. Here's why:
- Network streams: More data might arrive after you call
available() - File streams: The operating system might buffer more data than
available()reports - Zero doesn't mean empty:
available()returning0doesn't guarantee the stream is at its end—it just means no bytes are immediately ready
You should never use available() to allocate a buffer for the entire stream or assume it tells you the exact stream size. Instead, use it as a hint for optimization—for example, deciding whether to attempt a read immediately or do something else first.
Typical Pattern
Check availability, but always be ready for read() to return -1 (end-of-stream) or to block anyway:
int bytesAvailable = inputStream.available();
// bytesAvailable tells you *at least* this many bytes won't block
Key Takeaway: The available() method returns an estimate of bytes readable without blocking—useful as a hint, but never a guarantee of total stream content or exact availability.