Counting the Available Bytes

It's sometimes convenient to know how many bytes can be read before you attempt to read them. The InputStream class's available( ) method tells you how many bytes you can read without blocking. It returns 0 if there's no data available to be read.

public int available( ) 
 throws IOException

For example:

try {
 byte[] b = new byte[100];
 int offset = 0;
 while (offset < b.length) {
 int a = );
 int bytesRead =, offset, a);
 if (bytesRead == -1) break; // end of stream
 offset += bytesRead;
catch (IOException ex) {
 System.err.println("Couldn't read from!");

There's a potential bug in this code. There may be more bytes available than there's space in the array to hold them. One common idiom is to size the array according to the number available( ) returns, like this:

try {
 byte[] b = new byte[ )];;
catch (IOException ex) {
 System.err.println("Couldn't read from!");

This works well if you're going to perform a single read. For multiple reads, however, the overhead of creating multiple arrays is excessive. You should probably reuse the array and create a new array only if more bytes are available than will fit in the array.

The available( ) method in always returns 0. Subclasses are supposed to override it, but I've seen a few that don't. You may be able to read more bytes from the underlying stream without blocking than available( ) suggests; you just can't guarantee that you can. If this is a concern, place input in a separate thread so that blocked input doesn't block the rest of the program.

Basic I/O

Introducing I/O

Output Streams

Input Streams

Data Sources

File Streams

Network Streams

Filter Streams

Filter Streams

Print Streams

Data Streams

Streams in Memory

Compressing Streams

JAR Archives

Cryptographic Streams

Object Serialization

New I/O



Nonblocking I/O

The File System

Working with Files

File Dialogs and Choosers


Character Sets and Unicode

Readers and Writers

Formatted I/O with java.text


The Java Communications API


The J2ME Generic Connection Framework


Character Sets

Java I/O
Java I/O
ISBN: 0596527500
EAN: 2147483647
Year: 2004
Pages: 244 © 2008-2020.
If you may any questions please contact us: