Base de conocimientosCentro de exámenes
ESEspañol
Elegir idioma13

CKTIS / Java

Leer bytes UTF-8 y usar vistas de solo lectura de CharBuffer

Lee todos los bytes que devuelve un codificador UTF-8 y vuelve a consultar el CharBuffer consumido mediante una vista de solo lectura con posición propia.

Versión: Java SE 21

Sintaxis

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()

En Java SE 21, el intervalo activo de un búfer java.nio es [position(), limit()): la posición indica el inicio y el límite se excluye. remaining() devuelve limit() - position(), en bytes para ByteBuffer y en unidades de código UTF-16 (char), no puntos de código Unicode, para CharBuffer. position(int) acepta 0..limit(); limit(int) acepta 0..capacity() y reduce la posición si hace falta. Un valor no válido provoca IllegalArgumentException.

StandardCharsets.UTF_8.newEncoder().encode(cb) codifica el intervalo activo. Si tiene éxito, cb avanza hasta su límite sin borrar los caracteres. El ByteBuffer devuelto está listo para leer: su posición es cero y su límite marca el final de los bytes codificados. No llames a flip() sobre él. Para leerlo entero, crea byte[] bytes = new byte[encoded.remaining()] y llama a encoded.get(bytes). De forma predeterminada, el codificador indica una entrada mal formada mediante CharacterCodingException.

ByteBuffer.wrap(array) comparte el array de bytes sin copiarlo: la posición es cero y el límite y la capacidad son array.length. wrap(array, offset, length) conserva la capacidad del array completo, pero fija la posición en offset y el límite en offset + length. Un intervalo no válido provoca IndexOutOfBoundsException. Las lecturas relativas get(), get(dst) y get(dst, offset, length) leen un byte, llenan el array de destino o copian length bytes a partir del índice indicado en el destino, respectivamente. Avanzan la posición y, si faltan bytes, lanzan BufferUnderflowException sin una transferencia parcial. get(index) y get(index, dst[, offset, length]) son absolutos: no desplazan la posición y lanzan IndexOutOfBoundsException ante índices o intervalos no válidos.

asReadOnlyBuffer() comparte el contenido y toma la posición, el límite y la marca actuales como valores iniciales; después esos valores son independientes. put sobre la vista provoca ReadOnlyBufferException, pero las escrituras en el búfer modificable se ven en la vista. Si se crea después de codificar, la vista empieza con remaining() == 0. rewind() pone su posición a cero y descarta la marca sin cambiar el límite. Para volver a leer el mismo intervalo, restablece explícitamente la posición inicial si no era cero.

slice() comparte el intervalo restante sin mover el búfer de origen. La nueva posición es cero, el límite y la capacidad son la longitud del intervalo, la marca queda sin definir y se conserva el modo de solo lectura. slice(index, length) parte de un índice absoluto del búfer, no de un desplazamiento respecto a la posición. El intervalo debe caber en [0, limit()); uno vacío puede empezar en el límite. charAt(i) lee el char situado en position() + i sin avanzar y exige 0 <= i < remaining(). Un intervalo de slice o un índice de charAt no válido provoca IndexOutOfBoundsException. toString() devuelve un String inmutable del intervalo activo sin mover la posición.

Ejemplos

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());
    }
}

Resultado

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

Tres valores `char` producen cuatro bytes UTF-8. Tras escribir en el búfer original, la vista del subintervalo muestra `ZB`, pero el String anterior conserva `AB`.

Lecciones relacionadas

  • Java · Lección 51 · Avanzado · Versión: 2

Fuentes