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

CKTIS / Java

ByteBuffer — dados binários e estado do buffer

ByteBuffer armazena bytes e permite ler e escrever valores binários. Aprende a criar um buffer, definir a ordem dos bytes e controlar position e limit com flip, clear e compact.

Versão: Java SE 21; repository runtime, production runtime not attested

Sintaxe

ByteBuffer b = ByteBuffer.allocate(capacity).order(ByteOrder.BIG_ENDIAN);
b.putInt(value).putShort((short) count);
b.flip();
int valueRead = b.getInt();
short countRead = b.getShort();

java.nio.ByteBuffer é um buffer de bytes com capacidade fixa, também utilizado em operações de E/S. ByteBuffer.allocate(n) cria um buffer apoiado por um array, enquanto ByteBuffer.wrap(array) partilha um array existente sem o copiar. ByteBuffer.allocateDirect(n) cria um buffer direto: a JVM tenta reduzir as cópias durante a E/S nativa, mas não garante um melhor desempenho. ByteBuffer.isDirect() identifica este tipo de buffer.

ByteBuffer.capacity() devolve a capacidade fixa em bytes. ByteBuffer.position() indica o byte seguinte e ByteBuffer.limit() o primeiro índice inacessível; as sobrecargas que recebem um argumento definem estes valores. A condição é 0 <= position <= limit <= capacity, e ByteBuffer.remaining() equivale a limit - position.

ByteBuffer.put e ByteBuffer.get escrevem e leem bytes. ByteBuffer.putInt / ByteBuffer.getInt processam 4 bytes, e ByteBuffer.putShort / ByteBuffer.getShort processam 2. As operações relativas avançam a posição; as sobrecargas indexadas não a alteram, mas continuam a respeitar o limite. ByteBuffer.order() obtém a ordem dos bytes e order(ByteOrder.LITTLE_ENDIAN) altera-a; a predefinição é BIG_ENDIAN. Se não houver espaço ou dados suficientes numa operação relativa, ocorre, respetivamente, BufferOverflowException ou BufferUnderflowException.

Depois de escrever, ByteBuffer.flip() define o limite como a posição anterior e a posição como zero. ByteBuffer.compact() move os bytes não lidos para o início, coloca a posição imediatamente depois deles e define o limite como a capacidade, permitindo acrescentar mais dados. ByteBuffer.clear() define a posição como zero e o limite como a capacidade, mas não apaga os dados. O acesso concorrente a um buffer requer sincronização.

Exemplos

import java.nio.ByteBuffer;
import java.nio.ByteOrder;

public class Main {
    public static void main(String[] args) {
        ByteBuffer b = ByteBuffer.allocate(8).order(ByteOrder.LITTLE_ENDIAN);
        b.putInt(16909060).putShort((short) 7).put((byte) 9);
        System.out.println(b.position() + " " + b.limit() + " " + b.capacity());
        b.flip();
        System.out.println(b.getInt() + " " + b.getShort());
        b.compact();
        b.put((byte) 10);
        b.flip();
        System.out.println(b.remaining() + " " + b.get() + " " + b.get());
        b.clear();
        System.out.println(b.position() + " " + b.limit());
    }
}

Resultado

7 8 8
16909060 7
2 9 10
0 8

O código apresentado e o resultado declarado foram verificados num ambiente isolado pelo método registado na prova de verificação desta versão exata.

Fontes