Home » Core Java » nio » ByteBuffer » Convert between ByteBuffer and byte array

About Ilias Tsagklis

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

Convert between ByteBuffer and byte array

With this example we are going to demonstrate how to convert between ByteBuffers and byte arrays. In short, to make a conversion between a ByteBuffer and a byte array you should:

  • Create a byte array and wrap it into a ByteBuffer. The buffer’s capacity and limit will be the array’s length and its position will be zero.
  • Retrieve the bytes between the current position and the limit of the buffer. The new byte array’s length is set to the number of remaining elements in the buffer, using the remaining() API method and then the bytes are transfered from the buffer to the byte array, using the get(byte[] dst, int offset, int length) API method.
  • Retrieve all bytes in the buffer. First the buffer position is set to 0 and the buffer limit is set to its capacity, with the clear() API method, then the new byte array’s length is set to the buffer’s capacity and then again the get(byte[] dst, int offset, int length) API method transfers bytes from the buffer into the array.
 
Let’s take a look at the code snippet that follows.

// Create a byte array
byte[] bytes = new byte[10];

// Wrap a byte array into a buffer
ByteBuffer buf = ByteBuffer.wrap(bytes);

// Retrieve bytes between the position and limit
// (see Putting Bytes into a ByteBuffer)
bytes = new byte[buf.remaining()];

// transfer bytes from this buffer into the given destination array
buf.get(bytes, 0, bytes.length);

// Retrieve all bytes in the buffer
buf.clear();
bytes = new byte[buf.capacity()];

// transfer bytes from this buffer into the given destination array
buf.get(bytes, 0, bytes.length);

 
This was an example of how to convert between a ByteBuffer and a byte array 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