Get byte from ByteBuffer

With this example we are going to demonstrate how to read bytes from a ByteBuffer. Additionally we will show you several of ByteBuffer‘s API methods in order to share some light on how to randomly ready data from it.

package com.javacodegeeks.snippets.core;

import java.nio.ByteBuffer;

public class GetByteFromByteBuffer {
	public static void main(String[] args) {

		// Create a byte array
		byte[] bytes = { 0x00, 0x01, 0x02, 0x03, 0x04};

		// Wrap a byte array into a buffer
		ByteBuffer buf = ByteBuffer.wrap(bytes);
		// Get the buffer's capacity
		int capacity = buf.capacity();
		// Get the buffer's limit
		int limit = buf.limit();
		// Get the buffer's position
		int position = buf.position();
		System.out.println("Buffer capacity: " + capacity);
		System.out.println("Buffer limit: " + limit);
		System.out.println("Buffer position: " + position);

		// Absolute get method. Reads byte at given index (does not affect the position)
		byte b = buf.get(2);
		System.out.println("byte: " + b);
		// Set the position

		// Relative get method. Reads byte at buffer's current position and increments position.
		b = buf.get();
		System.out.println("byte: " + b);
		// Get remaining byte count
		int remainingBytes = buf.remaining();
		System.out.println("Buffer remaining bytes: " + remainingBytes);
		// Rewinds this buffer. The position is set to zero and the mark is discarded
		remainingBytes = buf.remaining();
		System.out.println("Buffer remaining bytes: " + remainingBytes);
		b = buf.get();
		System.out.println("byte: " + b);



Buffer capacity: 5
Buffer limit: 5
Buffer position: 0
byte: 2
byte: 3
Buffer remaining bytes: 1
Buffer remaining bytes: 5
byte: 0

This was an example of how to read bytes from a ByteBuffer in Java.

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Back to top button