Base de conhecimentoCentro de Exames
PT · PTPortuguês (Portugal)
Escolher idioma13

CKTIS / Java

Ler bytes UTF-8 e usar vistas CharBuffer só de leitura

Lê todos os bytes devolvidos pelo codificador UTF-8 e volta a consultar o CharBuffer através de uma vista só de leitura com posição independente.

Versão: Java SE 21

Sintaxe

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

Em Java SE 21, o intervalo ativo de um buffer java.nio é [position(), limit()): a posição indica o início e o limite é excluído. remaining() devolve limit() - position(), em bytes para ByteBuffer e em unidades de código UTF-16 (char), não em pontos de código Unicode, para CharBuffer. position(int) aceita 0..limit(); limit(int) aceita 0..capacity() e reduz a posição se necessário. Um valor inválido lança IllegalArgumentException.

StandardCharsets.UTF_8.newEncoder().encode(cb) codifica o intervalo ativo. Se a operação for bem-sucedida, cb avança até ao limite sem apagar os caracteres. O ByteBuffer devolvido está pronto a ler: a posição é zero e o limite assinala o fim dos bytes codificados. Não chames flip() nesse buffer. Para ler tudo, cria byte[] bytes = new byte[encoded.remaining()] e chama encoded.get(bytes). Por predefinição, o codificador assinala uma entrada malformada através de CharacterCodingException.

ByteBuffer.wrap(array) partilha o array de bytes sem o copiar: a posição é zero, e o limite e a capacidade são array.length. wrap(array, offset, length) mantém a capacidade do array inteiro, mas define a posição como offset e o limite como offset + length. Um intervalo inválido lança IndexOutOfBoundsException. As leituras relativas get(), get(dst) e get(dst, offset, length) leem um byte, preenchem o array de destino ou copiam length bytes a partir do índice indicado no destino, respetivamente. Avançam a posição e lançam BufferUnderflowException sem transferência parcial se faltarem bytes. As formas absolutas get(index) e get(index, dst[, offset, length]) não alteram a posição e lançam IndexOutOfBoundsException perante índices ou intervalos inválidos.

asReadOnlyBuffer() partilha o conteúdo e toma os valores atuais da posição, do limite e da marca como valores iniciais; depois, esses valores são independentes. put na vista lança ReadOnlyBufferException, mas as escritas no buffer modificável são visíveis na vista. Uma vista criada após a codificação começa com remaining() == 0. rewind() repõe a posição a zero e descarta a marca sem alterar o limite. Para reler o mesmo intervalo, repõe explicitamente a posição inicial se esta não era zero.

slice() partilha o intervalo restante sem deslocar o buffer de origem. A nova posição é zero, o limite e a capacidade correspondem ao comprimento do intervalo, a marca fica indefinida e o modo só de leitura é preservado. slice(index, length) usa um índice absoluto no buffer, não um deslocamento a partir da posição. O intervalo tem de caber em [0, limit()); um intervalo vazio pode começar no limite. charAt(i) lê o char em position() + i sem avançar e exige 0 <= i < remaining(). Um intervalo inválido em slice ou um índice inválido em charAt lança IndexOutOfBoundsException. toString() devolve uma String imutável do intervalo ativo, sem mudar a posição.

Exemplos

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

Três valores `char` produzem quatro bytes UTF-8. Depois de escrever no buffer original, a vista do segmento mostra `ZB`, mas a String anterior mantém `AB`.

Lições relacionadas

  • Java · Lição 51 · Avançado · Versão: 2

Fontes