CharBuffer
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: