Examples of CharEncoder Class

Example 1: Basic use of CharsetEncoder

In this example, the input string is encoded into bytes using the CharsetEncoder with UTF-8 character encoding.

It covers on how to construct a CharsetEncoder, encode the characters, place the input text within a CharBuffer, then output the data that has been encoded. It has basic error handling to address any issues that may come up during the encoding process.

Java




// Java Program to construct a 
// CharsetEncoder using CharBuffer
import java.nio.*;
import java.nio.charset.*;
  
//Driver class
public class Main {
      
      // Main method
      public static void main(String[] args){
  
        // Create a Charset
        Charset ch = Charset.forName("UTF-8");
  
        // Initialize a CharsetEncoder
        CharsetEncoder ec = ch.newEncoder();
  
        // Input string
        String str = "CharsetEncoder Example";
  
        // Wrap the input text in a CharBuffer
        CharBuffer charBuffer = CharBuffer.wrap(str);
  
        try {
            // Encode the characters
            ByteBuffer bf = ec.encode(charBuffer);
  
            // Print the encoded data
            String ans = new String(bf.array());
            System.out.println(ans);
        }
        catch (Exception e) {
            // Handle the exception
            e.printStackTrace();
        }
    }
}


Output:

CharsetEncoder Example

Example 2: Error Handling

The UTF-8 character encoding can encode only the characters that lie within the Unicode standard. There are some special characters or symbols that cannot be recognized by this encoding technique. In order to prevent problems, the errors need to be handled using some methods. In the below given example, we have given an input string which contains a special symbol ‘Ω’, that is not mappable using UTF-8. We use the ‘onUnmappableCharacter‘ and ‘CodingErrorAction.REPLACE‘ methods to replace these unmappable characters with any different character.

In the code below, whenever we encounter ‘Ω’, it is replaced by ‘?‘ which indicates that the special symbol is replaced with a fallback character for error handling.

Java




// Java Program for Error handling
// Using onUnmappableCharacter
import java.nio.*;
import java.nio.charset.*;
  
//Driver Class
public class Main {
      
      //Main method
      public static void main(String[] args){
        
        // Create a Charset
        Charset ch = Charset.forName("UTF-8");
  
        // Initialize a CharsetEncoder
        CharsetEncoder ec = ch.newEncoder();
  
        // Input string (with Ω as an unmappable character)
        String str = "Charset Ω Encoder";
  
        // Handle the error by replacing the unmappable
        // character with a question mark
        ec.onUnmappableCharacter(CodingErrorAction.REPLACE);
        ec.replaceWith("?".getBytes());
  
        // Wrap the string into a CharBuffer
        CharBuffer cb = CharBuffer.wrap(str);
  
        try {
            // Encode the characters
            ByteBuffer bf = ec.encode(cb);
  
            // Convert the ByteBuffer to a String
            String ans = new String(bf.array());
            System.out.println("Encoded String: " + ans);
        }
        catch (Exception e) {
            // Handle the exception
            System.err.println("Error: " + e.getMessage());
        }
        
    }
}


Output:

Encoded String: Charset ? Encoder

java.nio.charset.CharsetEncoder Class in Java

For the purpose of character encoding and decoding, java offers a number of classes in the ‘java.nio.charset’ package. The ‘CharsetEncoder’ class of this package performs the important task of encoding. In this article, let us understand this class, its syntax, different methods, and some examples of error handling and optimization techniques.

Similar Reads

What is a CharsetEncoder?

The ‘CharsetEncoder’ class is imported from ‘java.nio.charset’ package....

Constructors of CharsetEncoder

Constructor associated with CharsetEncoder and its description....

Methods of CharsetEncoder

Table of the methods associated with CharsetEncoder and its description....

Examples of CharEncoder Class

Example 1: Basic use of CharsetEncoder...

How to Optimize the Encoding?

...

Contact Us