CKTIS / Java
Charset — encoding and decoding text
java.nio.charset.Charset describes a mapping between Unicode code units and bytes. Learn how Charset.forName selects an encoding and how to create a decoder and encoder with explicit error handling.
Version: Java SE 21; repository runtime, production runtime not attested
Syntax
Charset cs = Charset.forName("UTF-8");
CharsetDecoder decoder = cs.newDecoder();
CharsetEncoder encoder = cs.newEncoder();java.nio.charset.Charset describes a named mapping between sequences of 16-bit Unicode code units and bytes. Decoding turns bytes into characters; encoding turns characters into bytes. The encoding must match the data format; choosing the wrong one can produce incorrect text without reporting an error.
Charset.forName("UTF-8") looks up an encoding by name or alias, ignoring case. An illegal name causes IllegalCharsetNameException, while an unsupported encoding causes UnsupportedCharsetException. For a fixed encoding, you can use StandardCharsets.UTF_8.
Charset.newDecoder() creates a CharsetDecoder that converts a ByteBuffer into a CharBuffer. If the charset supports encoding, Charset.newEncoder() creates a CharsetEncoder for the reverse direction. Some charsets support only decoding: if canEncode() returns false, newEncoder() throws UnsupportedOperationException. A Charset object is immutable and safe to share across threads, but encoders and decoders are not safe for concurrent use by multiple threads.
New encoders and decoders default to CodingErrorAction.REPORT for malformed input and unmappable characters. Their single-argument encode and decode methods can therefore throw CharacterCodingException. In contrast, the convenience methods Charset.encode and Charset.decode replace problematic data. Use onMalformedInput and onUnmappableCharacter to choose an error policy explicitly.
The example encodes caf\u00e9 as UTF-8 and decodes the result. It checks the byte count and text equality without depending on terminal character rendering. The encoding result is already ready for reading; do not call flip() on it before decoding.
Examples
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
public class CharsetDemo {
public static void main(String[] args) throws CharacterCodingException {
Charset cs = Charset.forName("UTF-8");
String text = "caf\u00e9";
ByteBuffer bytes = cs.newEncoder().encode(CharBuffer.wrap(text));
System.out.println("bytes=" + bytes.remaining());
String decoded = cs.newDecoder().decode(bytes).toString();
System.out.println("roundTrip=" + text.equals(decoded));
}
}Result
bytes=5 roundTrip=true
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.