What is the java.nio.CharBuffer class in Java?
Overview
The java.nio class represents
A channel is like a regular stream, but unlike a
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.
It is a finite sequence of elements of any particular primitive type.
Even though
java.niosupports non-blocking IO, it is NOT an asynchronous class because some operations are actually blocking, e.g., file IO.
Buffers have three essential properties.
-
capacity: Capacity refers to the total size of the buffer. It always remains constant.
-
limit: The limit determines how many elements you can read or write from the buffer.
-
position: The position determines the index from which to initiate reading or writing a buffer.
The CharBuffer class
This class describes four kinds of operations upon char buffers:
-
Relative and absolute
getandputmethods that read and write single chars. -
Relative bulk
getmethods give contiguous chars sequences from this buffer into an array. -
Relative bulk
putmethods give contiguous sequences of chars from a char array, a string, or another char buffer into this buffer. -
The class gives methods for duplicating, compacting, and slicing a char buffer.
Class methods
| Method name | Description |
|---|---|
allocate(int capacity) |
The allocate method allocates a new char buffer. |
append(char c) |
The append method appends the specified char to the buffer. |
compact() |
The compact method compacts the buffer. |
array() |
The array method returns the char array that backups up the buffer. |
arrayOffset() |
The arrayOffset method returns the offset within this buffer’s backing array of the first element of the buffer. |
A complete list of class methods can be found here.
Code
The code here shows an example of how to create a CharBuffer object:
import java.nio.*;import java.util.*;class HelloWorld {public static void main( String args[] ) {int CAPACITY = 10;char [] charArray = {'a', 'b', 'c'};CharBuffer buffer1 = CharBuffer.allocate(CAPACITY);CharBuffer buffer2 = CharBuffer.wrap(charArray);buff1.put(0, 'd');System.out.println(Arrays.toString(buffer1.array()));System.out.println(Arrays.toString(buffer2.array()));}}
Explanation
-
buffer1is created using the allocate() method. -
buffer2is made by wrapping an already existingchararray calledcharArrayinto a buffer using thewrapmethod. -
The
.arraymethod returns the char array that backs up the buffer.