Home » Core Java » nio » ByteBuffer » Use ByteBuffer to store Strings

About Ilias Tsagklis

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

Use ByteBuffer to store Strings

This is an example of how to store Strings using a ByteBuffer in Java. In order to use a ByteBuffer to store Strings in Java we have to :

  • Allocate a new ByteBuffer and set its size to a number large enough in order to avoid buffer to overflow when putting bytes to it
  • Use the asCharBuffer() API method so as to be able to put characters directly into the byte buffer
  • Using the put(String) API method we can put a String directly to the byte buffer
  • The toString() API method returns the string representation of the ByteBuffer’s contents. Do not forget to flip() the ByteBuffer since the toString() API method displays ByteBuffer’s contents from the current buffer’s position on-wards
  • as shown in the code snippet below.

 

package com.javacodegeeks.snippets.core;

import java.nio.ByteBuffer;
import java.nio.CharBuffer;

public class UseByteBufferToStoreStrings {
	
	public static void main(String[] args) {

		// Allocate a new non-direct byte buffer with a 50 byte capacity


    // set this to a big value to avoid BufferOverflowException
		ByteBuffer buf = ByteBuffer.allocate(50); 
		
		// Creates a view of this byte buffer as a char buffer
		CharBuffer cbuf = buf.asCharBuffer();

		// Write a string to char buffer
		cbuf.put("Java Code Geeks");

		// Flips this buffer.  The limit is set to the current position and then
		// the position is set to zero.  If the mark is defined then it is discarded
		cbuf.flip();
		
		String s = cbuf.toString();  // a string

		System.out.println(s);
		
	}

}

Output:

Java Code Geeks

This was an example of how to use a ByteBuffer to store Strings 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