The java.nio
class represents New IO, an alternative to the regular IO API in Java. java.nio
allows you to use channels and buffers to do non-blocking IO.
A channel is like a regular stream, but unlike a stream, a single channel can be used to read and write data, whereas a stream is usually only one-way. You can write to channels asynchronously. Channels usually write to and read from buffers.
A buffer is a block of memory where data can be written and be read later on. A buffer is a finite sequence of elements of any particular primitive type.
ShortBuffer
classThe ShortBuffer
class in Java is used to hold a sequence of integer values to be used in an IO operation.
This class defines four categories of operations on the short buffer:
put
and get
methods that can read and write single shorts.get
methods that assign adjacent sequences of shorts from this buffer into an array.put
methods that assign adjacent sequences of shorts from a short array or some other short buffer into this buffer.ShortBuffer
classSome of the most used methods are described in the table below.
Method | Description |
---|---|
allocate(int capacity) |
Allocates a new short buffer. |
array() |
Returns the short array that backs the short buffer (optional operation). |
compact() |
Compacts the buffer (optional operation). |
asReadOnlyBuffer() |
Creates a new, read-only buffer that shares this buffer’s content. |
The list of all the methods can be found here.
import java.nio.*;import java.util.*;class HelloWorld {public static void main( String args[] ) {int CAPACITY = 10;short [] shortArray = {(short)100, (short)20};ShortBuffer buff1 = ShortBuffer.allocate(CAPACITY);ShortBuffer buff2 = ShortBuffer.wrap(shortArray);buff1.put(1, (short)10);System.out.println(Arrays.toString(buff1.array()));System.out.println(Arrays.toString(buff2.array()));}}
buff1
and buff2
, are created.buff1
is created with the allocate
method, whereas buff2
is made by wrapping an already existing short array called shortArray
into a buffer using the wrap
method.