ByteBuffer

Put byte into ByteBuffer

This is an example of how to put bytes into a ByteBuffer in Java. Additionally we will demonstrate several of ByteBuffer‘s API methods in order to share some light on how to randomly write data to it.
 
 
 
 
 
 
 
 

package com.javacodegeeks.snippets.core;

import java.nio.ByteBuffer;

public class PutByteIntoByteBuffer {
	
	public static void main(String[] args) {
		
		// Allocate a new non-direct byte buffer with a 5 byte capacity
		// The underlying storage is a byte array.
		ByteBuffer buf = ByteBuffer.allocate(5);
		
		// 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);

		buf.put((byte)0x01); // at position 0

		position = buf.position();
		System.out.println("Buffer position: " + position);
		
		// Set the position
		buf.position(3);
		
		position = buf.position();
		System.out.println("Buffer position: " + position);

		// Use the relative put()
		buf.put((byte)0x02);
		
		position = buf.position();
		System.out.println("Buffer position: " + position);
		
		// 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
		buf.rewind();
		
		remainingBytes = buf.remaining();
		System.out.println("Buffer remaining bytes: " + remainingBytes);
		
	}

}

Output:

Buffer capacity: 5
Buffer limit: 5
Buffer position: 0
Buffer position: 1
Buffer position: 3
Buffer position: 4
Buffer remaining bytes: 1
Buffer remaining bytes: 5

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

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

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

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button