CKTIS / Java
CharsetEncoder — encoding characters into bytes
CharsetEncoder converts Unicode characters into bytes in a selected charset. It supports explicit error handling and encoding either a complete buffer or successive chunks of text.
Version: Java SE 21; repository runtime, production runtime not attested
Syntax
CharsetEncoder encoder = charset.newEncoder();
ByteBuffer bytes = encoder.encode(CharBuffer.wrap(text));
encoder.reset();
CoderResult result = encoder.encode(in, out, endOfInput);CharsetEncoder in java.nio.charset encodes characters into bytes; CharsetDecoder does the reverse. Create an encoder through charset.newEncoder(), selecting the charset explicitly.
CharsetEncoder.encode(CharBuffer) performs reset, encoding, and final flushing. It returns a new ByteBuffer ready for reading: its position is zero and its limit marks the end of the data. Do not invoke this method during an ongoing operation.
encode(in, out, endOfInput) advances buffer positions and returns CoderResult. On OVERFLOW, drain bytes; on UNDERFLOW, preserve unconsumed characters before adding more. Start a new operation with reset() (unnecessary for first use); finish encoding with endOfInput = true, then call flush(out) until UNDERFLOW.
The default REPORT distinguishes malformed UTF-16 from valid characters unrepresentable in the charset. The single-buffer overload throws CharacterCodingException; the streaming overload returns an error result. IGNORE and REPLACE can lose information. Do not share an encoder between concurrently executing threads.
Examples
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.StandardCharsets;
public class Main {
public static void main(String[] args) throws CharacterCodingException {
CharsetEncoder encoder = StandardCharsets.UTF_8.newEncoder();
ByteBuffer bytes = encoder.encode(CharBuffer.wrap("A\u20AC"));
while (bytes.hasRemaining()) {
System.out.println(bytes.get() & 0xFF);
}
}
}Result
65 226 130 172
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.