ByteBuffer
Put byte into ByteBuffer
This is an example of how to put bytes into a ByteBuffer in Java. Additionally we will demonstrate several ofByteBuffer‘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 capacityint capacity = buf.capacity();// Get the buffer's limitint limit = buf.limit();// Get the buffer's positionint 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 0position = buf.position();System.out.println("Buffer position: " + position);// Set the positionbuf.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 countint remainingBytes = buf.remaining();System.out.println("Buffer remaining bytes: " + remainingBytes);// Rewinds this buffer. The position is set to zero and the mark is discardedbuf.rewind();remainingBytes = buf.remaining();System.out.println("Buffer remaining bytes: " + remainingBytes);}}Output:
Want to be a Java NIO Master ?
Subscribe to our newsletter and download the JDBCUltimateGuideright now!
In order to help you master Java NIO Library, we have compiled a kick-ass guide with all the major Java NIO features and use cases! Besides studying them online you may download the eBook in PDF format!

Thank you!
We will contact you soon.
Buffer capacity: 5Buffer limit: 5Buffer position: 0Buffer position: 1Buffer position: 3Buffer position: 4Buffer remaining bytes: 1Buffer remaining bytes: 5This was an example of how to write bytes in a ByteBuffer in Java.
Do you want to know how to develop your skillset to become aJava Rockstar?
Subscribe to our newsletter to start Rockingright now!
To get you started we give you our best selling eBooks forFREE!
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 ....
I agree to theTerms andPrivacy Policy

Thank you!
We will contact you soon.
Ilias Tsagklis
Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor atJava Code Geeks.



