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.

 

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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:

Want to be a Java NIO Master ?
Subscribe to our newsletter and download the JDBC Ultimate Guide right 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!

Java Code Geeks

This was an example of how to use a ByteBuffer to store Strings in Java.

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 ....
I agree to the Terms and Privacy Policy

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
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button