java.nio.charset.CodingErrorAction Class in Java
Last Updated :
21 Mar, 2024
In Java programming, Character encoding plays an important when we talk about handling data and information across different systems. The java.nio.charset package contains classes for managing character encoding and decoding. CodingErrorAction class is one of the package’s core classes. This class describes the actions to be taken when an encoding or decoding issue arises.
The java.nio.charset.CodingErrorAction class is an enum representing different actions to be handled in response to encoding or decoding errors. These actions help the developer to define how the encoding or decoding process will proceed once unexpected situations occur.
Methods of java.nio.charset.CodingErrorAction Class
Method
| Description
|
---|
toString()
| Returns a string describing this action.
|
Fields of java.nio.charset.CodingErrorAction Class
Field
| Description
|
---|
IGNORE
| Error should be handled by dropping the erroneous input and resuming the coding operation
|
---|
REPLACE
| Error should be handled by dropping the erroneous input, appending the replacement value to the output buffer
|
---|
REPORT
| Error is to be reported to the developer
|
---|
Example
Let’s take an example where we will be using java.nio.charset.CodingErrorAction IGNORE property to ignore the exceptions caused during encoding or decoding.
Java
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CodingErrorAction;
public class CodingErrorActionShortExample {
public static void main(String[] args) {
Charset charset = Charset.forName("ISO-8859-1");
CharsetEncoder encoder = charset.newEncoder();
// Set the coding error action to IGNORE
encoder.onMalformedInput(CodingErrorAction.IGNORE)
.onUnmappableCharacter(CodingErrorAction.IGNORE);
String input = "Hello, 你好, नमस्ते";
CharBuffer charBuffer = CharBuffer.wrap(input);
ByteBuffer byteBuffer = ByteBuffer.allocate(50);
try {
encoder.encode(charBuffer, byteBuffer, true);
byteBuffer.flip();
while (byteBuffer.hasRemaining()) {
System.out.print((char) byteBuffer.get());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:
Hello, ,
Share your thoughts in the comments
Please Login to comment...