java.io.UnsupportedEncodingException in java with Examples

When an unsupported character encoding scheme is applied to Java strings or bytes, the java.io.UnsupportedEncodingException is raised. The specified encoding format's bytes are obtained from the requested string using the Java String getBytes function. Java.io.UnsupportedEncodingException is thrown by the String getBytes function using the specified encoding format if Java does not support the encoding format.

The original binary's interpretation into a character is determined by the character encoding. The encoding used by English Windows computers by default in CP1252. Alternative systems and languages may employ distinct default encodings. Character encoding schemes that are often used are UTF-8 and UTF-16. Java allows for the interpretation of raw bytes into strings using the String.getBytes() and StringCoding.encode() methods.

Class Viewer

Syntax:

Since there is no support for the character encoding. Let's continue by looking over this class's constructors, which are as follows:

  1. UnsupportedEncodingException(): creates an UnsupportedEncodingException without providing a detailed explanation.
  2. UnsupportedEncodingException(String s): creates an UnsupportedEncodingException with providing a detailed explanation.

Implementation:

Let's now figure out how to get rid of the problem. With the help of the throw java.io.UnsupportedEncodingException example given below, we shall continue. The name of the "UTF" encoding scheme is not recognised.

Java cannot convert a string to bytes if the encoding strategy is either unsupported or unknown. This is the reason for this. If Java detects an unsupported or unknown encoding technique, it will issue java.io.UnsupportedEncodingException.

Example 1:

FileName: UnsupportedException1.java

Output:

Exception in thread "main" java.io.UnsupportedEncodingException: UTF
at java.base/java.lang.String.lookupCharset(String.java:841)
at java.base/java.lang.String.getBytes(String.java:1770)
	at UnsupportedException1.main(UnsupportedException1.java:10)

To solve this issue, the String.getBytes method, the name of the Java-supported encoding scheme must be provided. Before moving on, please take a look at the list of available methods here.

Therefore, when more control over the encoding process is needed, the CharsetEncoder class should be utilised. An array of bytes is returned by the String.getBytes function.

Example 2:

FileName: UnsupportedException2.java

Output:

The Given input String : Welcome to the World
The Output bytes is given by : [B@7e9e5f8a





Latest Courses