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.

Want to know how to develop your skillset to become a Java Rockstar?

Join our newsletter to start rocking!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

I have read and agree to the terms & conditions

 

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
Inline Feedbacks
View all comments
Back to top button