바이트 버퍼
바이트 버퍼 (ByteBuffer)
바이트를 담는 버퍼예요. 직접 버퍼와 힙 버퍼 두 종류가 있고, 채널 I/O에서 가장 널리 사용되는 버퍼 타입입니다.
본문
ByteBuffer는 바이트를 담는 버퍼예요. 버퍼는 data의 시퀀스를 담는 컨테이너로, ByteBuffer는 그 중 바이트 타입을 위한 것입니다.
버퍼의 핵심 속성:
- capacity — 버퍼가 담을 수 있는 원소의 총 수.
- limit — 읽거나 쓰면 안 되는 첫 원소의 인덱스.
- position — 다음에 읽거나 쓸 원소의 인덱스.
ByteBuffer는 두 가지 종류로 나뉘어요.
- 힙 버퍼(heap buffer) — 배열 뒤에 놓이고 제약이 가장 적습니다.
- 직접 버퍼(direct buffer) — 네이티브 메모리에서 할당되며, 채널 I/O에 사용할 때 더 효율적일 수 있어요.
주요 메서드:
public static ByteBuffer allocate(int capacity)
public static ByteBuffer allocateDirect(int capacity)
public static ByteBuffer wrap(byte[] array, int offset, int length)
public abstract ByteBuffer put(byte b)
public abstract ByteBuffer get(byte[] dst)
public final ByteBuffer putInt(int value)
public final int getInt()
public ByteBuffer order(ByteOrder bo)
public ByteOrder order()
allocate()— 힙에 새 버퍼를 할당해요.allocateDirect()— 직접 버퍼를 할당해요.wrap()— 기존 배열을 버퍼로 감싸요.putInt()/getInt()같은 메서드로 다양한 기본 타입을 넣고 뺄 수 있어요.order()로 바이트 순서(빅/리틀 엔디언)를 설정할 수 있습니다.
ByteBuffer는 Buffer의 sealed 하위 클래스 중 하나이며, 채널 I/O와 네트워크 프로그래밍에서 핵심적으로 사용돼요.