CKTIS / Java
Draining UTF-8 bytes and reading shared CharBuffer views
Drain the actual bytes returned by a UTF-8 encoder, then inspect the consumed CharBuffer through a read-only view with its own cursor.
Version: Java SE 21
Syntax
Java SE 21 — java.nio.ByteBuffer
static ByteBuffer wrap(byte[] array)
static ByteBuffer wrap(byte[] array, int offset, int length)
int remaining()
byte get()
ByteBuffer get(byte[] dst)
ByteBuffer get(byte[] dst, int offset, int length)
byte get(int index)
ByteBuffer get(int index, byte[] dst)
ByteBuffer get(int index, byte[] dst, int offset, int length)
java.nio.CharBuffer
CharBuffer asReadOnlyBuffer()
CharBuffer rewind()
int remaining()
int limit()
CharBuffer limit(int newLimit)
int position()
CharBuffer position(int newPosition)
CharBuffer slice()
CharBuffer slice(int index, int length)
char charAt(int index)
String toString()In Java SE 21, a java.nio buffer's active range is [position(), limit()): position is the start, and limit is exclusive. remaining() returns limit() - position() in bytes for ByteBuffer and in UTF-16 code units (char values), not Unicode code points, for CharBuffer. position(int) accepts 0..limit(); limit(int) accepts 0..capacity() and lowers position if necessary. Invalid setter values throw IllegalArgumentException.
StandardCharsets.UTF_8.newEncoder().encode(cb) encodes the active range. On success, cb advances to its limit; the characters are not erased. The returned ByteBuffer is ready to read: its position is zero and its limit marks the end of the encoded bytes. Do not call flip() on it. Drain it by allocating byte[] bytes = new byte[encoded.remaining()] and calling encoded.get(bytes). The encoder reports malformed input by default via CharacterCodingException.
ByteBuffer.wrap/remaining/get work with bytes already in memory. wrap(array) shares the byte array without copying, with position zero and limit and capacity equal to array.length. wrap(array, offset, length) retains the full array capacity but sets position to offset and limit to offset + length; an invalid range throws IndexOutOfBoundsException. Relative get() reads one byte, get(dst) fills the destination array, and get(dst, offset, length) copies length bytes starting at the destination offset. They advance position and throw BufferUnderflowException without a partial transfer if too few bytes remain. Absolute get(index) and get(index, dst[, offset, length]) leave position unchanged and throw IndexOutOfBoundsException for invalid indices or ranges.
CharBuffer.asReadOnlyBuffer/rewind/remaining/limit/position/slice/charAt/toString let you revisit the input without moving its cursor. asReadOnlyBuffer() shares content and takes the current position, limit, and mark as its initial values; those values are then independent. put through the view throws ReadOnlyBufferException, but writes through the writable buffer are visible in the view. A view made after encoding initially has remaining() == 0. rewind() sets the view's position to zero and discards its mark without changing its limit. It does not restore a previous nonzero start; set that position explicitly to reread the same range.
slice() shares the remaining range without moving the parent. The new view starts at position zero, has limit and capacity equal to the range length, has no mark, and preserves read-only status. slice(index, length) instead starts at an absolute buffer index, not an offset from position; the range must fit within [0, limit()), and an empty range may start at the limit. charAt(i) reads the char at position() + i without advancing and requires 0 <= i < remaining(). Invalid indexed slice ranges or charAt indices throw IndexOutOfBoundsException. toString() returns an immutable String for the active range without moving position.
Examples
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.StandardCharsets;
import java.util.HexFormat;
public class BufferDemo {
public static void main(String[] args) throws CharacterCodingException {
CharBuffer cb = CharBuffer.wrap(new char[] {'[', '\u00E9', 'A', 'B', ']'});
cb.position(1).limit(4);
ByteBuffer encoded = StandardCharsets.UTF_8.newEncoder().encode(cb);
System.out.println("input position=" + cb.position() + ", remaining=" + cb.remaining());
byte[] bytes = new byte[encoded.remaining()];
encoded.get(bytes);
System.out.println("utf8=" + HexFormat.of().formatHex(bytes)
+ ", remaining=" + encoded.remaining());
ByteBuffer suffix = ByteBuffer.wrap(bytes, 2, 2);
System.out.println("suffix first=" + suffix.get() + ", remaining=" + suffix.remaining());
CharBuffer view = cb.asReadOnlyBuffer();
System.out.println("view initial remaining=" + view.remaining());
view.rewind().position(2);
CharBuffer tail = view.slice();
System.out.println("charAt(0)=" + view.charAt(0) + ", view position=" + view.position()
+ ", input position=" + cb.position() + ", slice position=" + tail.position());
String snapshot = tail.toString();
cb.put(2, 'Z');
System.out.println("snapshot=" + snapshot + ", slice now=" + tail.toString());
}
}
Result
input position=4, remaining=0 utf8=c3a94142, remaining=0 suffix first=65, remaining=1 view initial remaining=0 charAt(0)=A, view position=2, input position=4, slice position=0 snapshot=AB, slice now=ZB
Three char values produce four UTF-8 bytes. After a write through the original buffer, the slice shows `ZB` while the earlier String still holds `AB`.
Related lessons
- Java · Lesson 51 · Advanced · Version: 2