O'Reilly logo

Java I/O by Elliotte Rusty Harold

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required