Home » Core Java » nio » CharBuffer » Convert String to byte array UTF encoding

About Byron Kiourtzoglou

Byron Kiourtzoglou
Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.

Convert String to byte array UTF encoding

With this example we are going to demonstrate how to convert a String to byte array and vice-versa using the default character encoding in Java. In short, to perform the aforementioned conversion, we are going to use classes from the NIO package in Java so as to convert every character from the target String to its byte equivalent. Namely we :

  • Use the toCharArray() API method of the String class to get its char array equivalent. Every character in Java is represented as a fixed-width 16-bit entity
  • We construct an empty byte array to hold the bytes for each character of the target String – the size of the byte array should be double the size of the character array
  • We use Java NIO package ByteBuffer class to wrap the newly created byte array and we dictate by using the asCharBuffer() API method that we are going to use the specific ByteBuffer as CharBuffer
  • Last but not least we insert all characters from the character array to the CharBuffer and thus to the proxied byte array

as shown in the code snippets below.

public static byte[] stringToBytesUTFNIO(String str) {
 char[] buffer = str.toCharArray();
 byte[] b = new byte[buffer.length << 1];
 CharBuffer cBuffer = ByteBuffer.wrap(b).asCharBuffer();
 for(int i = 0; i < buffer.length; i++)
  cBuffer.put(buffer[i]);
 return b;
}
public static String bytesToStringUTFNIO(byte[] bytes) {
 CharBuffer cBuffer = ByteBuffer.wrap(bytes).asCharBuffer();
 return cBuffer.toString();
}

This was an example of how to convert a String to byte array in Java.

Related Article:

(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