Reading Byte Arrays

As already mentioned, the DataInputStream class has the usual two methods for reading bytes into a byte array:

public int read(byte[] data) throws IOException
public int read(byte[] data, int offset, int length) throws IOException

Neither of these methods guarantees that all the bytes requested will be read. Instead, you’re expected to check the number of bytes actually read, then call read() again for a different part of the array as necessary. For example, to read 1024 bytes from the InputStream in into the byte array data:

int offset = 0;
while (true){
  int bytesRead = in.read(data, offset, data.length - offset);
  offset += bytesRead;
  if (bytesRead == -1 || offset >= data.length) break;
}

The DataInputStream class has two readFully() methods that provide this logic. Each reads repeatedly from the underlying input stream until the array data or specified portion thereof is filled.

public final void readFully(byte[] data) throws IOException
public final void readFully(byte[] data, int offset, int length) 
                  throws IOException

If the data runs out before the array is filled and no more data is forthcoming, then an IOException is thrown.

Get Java I/O now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.