Home  >  Core Java

Encode and Decode in Java NIO

By Arvind Rai, December 13, 2013
In java encode and decode from one charset to another charset can be done using java NIO API. A ByteBuffer with any charset can be changed to CharBuffer in Unicode charset. Two class CharsetDecoder and CharsetEncoder play the role of encoding and decoding between ByteBuffer and CharBuffer.

CharsetDecoder in Java NIO

CharsetDecoder decodes the sequence of bytes or array of bytes in Unicode characters. While decoding from ByteBuffer to CharBuffer , CoderResult is obtained. CoderResult contains the error if any and its explanation.

CharsetEncoder in Java NIO

CharsetEncoder plays the opposite role of CharsetDecoder . CharsetEncoder can encode the Unicode characters again into sequences of bytes. CharsetEncoder also returns CoderResult that gives the information of any error.

Charset.newDecoder() in Java NIO

To CharsetDecoder, Charset.newDecoder() is used. We need to create an object of Charset by passing the charset canonical name and then by that object we can get an object of CharsetDecoder.

Charset.newEncoder() in Java NIO

To instantiate CharsetEncoder , like CharsetDecoder, we need to get an object of Charset and then by newEncoder () method, we can instantiate the CharsetEncoder object.

CoderResult in Java NIO

java.nio.charset.CoderResult is the result of encoding and decoding between the sequences of bytes and Unicode characters. CoderResult represents the error if any. It can be like Underflow, Overflow, malformed-input error and unmappable-character error.
package com.concretepage.nio.charset;
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 EncodeDecodeExample {
	public static void main(String[] args) throws CharacterCodingException {
		 Charset charset = Charset.forName("UTF-8");
		 CharsetDecoder chdecoder = charset.newDecoder();
		 CharsetEncoder chencoder = charset.newEncoder();
		 String s = "Encode and Decode Example.";
		 ByteBuffer byteBuffer= ByteBuffer.wrap(s.getBytes());
		 CharBuffer charBuffer = chdecoder.decode(byteBuffer);
		 ByteBuffer newByteBuff = chencoder.encode(charBuffer); 
	        	char ch = (char) newByteBuff.get();


Encode and Decode Example.

©2019 concretepage.com | Privacy Policy | Contact Us