Home » Core Java » nio » ByteBuffer » Put byte into ByteBuffer

About Ilias Tsagklis

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

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.

(No Ratings Yet)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

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

 

Leave a Reply

avatar
  Subscribe  
Notify of