Reading and writing arrays to a NIO buffer

The ByteBuffer class provides methods for reading and writing a byte array (or section of a byte array) to or from the buffer. For example, to write an entire byte array to the buffer's current position, we use:

byte[] arr = new byte[10];
// ... put some useful values in arr ...
ByteBuffer bb = ByteBuffer.allocate(50);
bb.put(arr);

Note that the entire array is written, and an exception is immediately thrown if the entire array could not fit into the buffer. In other words, no bytes are written unless the entire array can fit into the remainder of the buffer at its current position. The type of exception thrown is a BufferOverflowException. Like ArrayIndexOutOfBoundsException, this is an unchecked exception, meaning that the calling code doesn't explicitly have to catch it.

Reading an array

To read or get() a byte array from a ByteBuffer, you might have expected a method that returns a byte array. But in fact:

In other words, we need to manually create the array that we want to fill with bytes from the buffer, and then pass this array into ByteBuffer.read(). This pattern of supplying the array in advance is similar to other methods in the JDK that read data into byte buffers (such as InputStream.read()). The advantages are efficiency and flexibility– we can perform multiple reads into the same array (i.e. re-use the array object) without having the overhead of creating a new array each time; and we can read different data into different parts of an array without having to perform extra copy operations.

Reading and writing arrays of floats, ints etc

In the next section, we look at using the various "wrapper buffer" types such as IntBuffer, FloatBuffer etc to read and write primitive arrays of various types to an underlying buffer.


If you enjoy this Java programming article, please share with friends and colleagues. Follow the author on Twitter for the latest news and rants.

Editorial page content written by Neil Coffey. Copyright © Javamex UK 2021. All rights reserved.