ByteBuffer

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.

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