CharBuffer
Convert Between Character Set Encodings with CharBuffer
In this example we shall show you how to convert between character set encodings with a CharBuffer in Java. To achieve character set conversions in Java one should perform the following steps:
- Use the Charset class to get the Charset object for utilizing the specific character set
- Use the
newDecoder()
API method of the Charset object to construct a new decoder for this charset - Use the
newEncoder()
API method of the Charset object to construct a new encoder for this charset - Use the CharBuffer class to wrap the target character sequence into a buffer
- Use the
encode(CharBuffer)
anddecode(ByteBuffer)
API methods of the encoder and decoder objects respectively to convert to/from the specific character encoding – here “ISO-8859-1”
as demonstrated in the code snippet that follows.
package com.javacodegeeks.snippets.core; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.CharacterCodingException; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.CharsetEncoder; public class ConvertBetweenCharacterSetEncodingsWithCharBuffer { public static void main(String[] args) { try { // Returns a charset object for the named charset. Charset charset = Charset.forName("ISO-8859-1"); // Constructs a new decoder for this charset. CharsetDecoder decoder = charset.newDecoder(); // Constructs a new encoder for this charset. CharsetEncoder encoder = charset.newEncoder(); // Wrap the character sequence into a buffer. CharBuffer uCharBuffer = CharBuffer.wrap("Java Code Geeks"); // Encode the remaining content of a single input character buffer to a new byte buffer. // Converts to ISO-8859-1 bytes and stores them to the byte buffer ByteBuffer bbuf = encoder.encode(uCharBuffer); // Decode the remaining content of a single input byte buffer to a new character buffer. // Converts from ISO-8859-1 bytes and stores them to the character buffer CharBuffer cbuf = decoder.decode(bbuf); String s = cbuf.toString(); System.out.println("Original String is: " + s); } catch (CharacterCodingException e) { System.out.println("Character Coding Error: " + e.getMessage()); } } }
Output:
Original String is: Java Code Geeks
This was an example of how to convert between character set encodings in Java.