InputStream.available estimates bytes readable without blocking; it is not an end-of-stream test or total-size query.
Java InputStream.available is not the remaining stream length
Read until the stream contract ends
A stream may have data even when available returns zero. The fixture overrides available to report zero while three bytes remain, then reads those bytes normally. Code that allocates available bytes and calls the job complete would silently drop the record.
Use a read loop or a bounded framed read instead. If the input format has a length prefix, validate that prefix independently of available.
Avoid false size assumptions
Some in-memory streams return a convenient remaining count, but code that works only on those streams can fail on sockets and wrappers. available is a scheduling hint for a narrow purpose. It does not replace protocol framing, EOF handling, or an input budget.
Working program
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
public class InventoryInputAvailability {
public static void main(String[] args) throws IOException {
InputStream source = new ByteArrayInputStream(new byte[] {47, 82, 15}) {
@Override public synchronized int available() { return 0; }
};
System.out.println("available=" + source.available());
int total = 0;
int next;
while ((next = source.read()) != -1) total += next;
System.out.println("sum=" + total);
}
}Output
available=0
sum=144Cost and ownership
This single-byte loop is O(n) calls and constant storage; a buffered block read reduces call overhead for larger inputs. The important boundary is semantic: only read returning -1 identifies EOF for this stream.
Common Mistakes
- Do not treat available equal to zero as EOF.
- Do not allocate the entire input from available.
- Do not generalize an in-memory stream's available behavior to network streams.
Read next
Java InputStream short reads: assemble a complete record header, Java readNBytes: reject a truncated payload after the header, Java byte streams: partial reads and bounded copying, Java file I/O: UTF-8, streaming reads, and path ownership.
