CharsetEncoder Replaces Unmappable Input

Choose between REPORT and REPLACE on CharsetEncoder so unmappable characters either stop the encode with an exception or become a placeholder byte.

JavaResilience

Code

snippet
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 EuroSignProbe {

    public static void main(String[] args) {
        Charset latin1 = Charset.forName("ISO-8859-1");
        String text = "café € 99"; // '€' 不在 ISO-8859-1 里,是 unmappable 字符

        // 默认动作是 REPORT:遇到不可映射字符直接抛异常,编码中断
        try {
            latin1.newEncoder().encode(CharBuffer.wrap(text));
        } catch (Exception e) {
            System.out.println("strict encode threw: " + e.getClass().getSimpleName());
        }

        // REPLACE:不可映射字符换成占位字节,编码继续走完而不是失败
        CharsetEncoder lenient = latin1.newEncoder()
                .onMalformedInput(CodingErrorAction.REPLACE)
                .onUnmappableCharacter(CodingErrorAction.REPLACE);
        ByteBuffer bytes = lenient.encode(CharBuffer.wrap(text));
        String round = new String(bytes.array(), 0, bytes.remaining(), latin1);
        System.out.println("lenient encode: " + round);
        System.out.println("bytes written: " + bytes.remaining());
    }
}

How it works

One way to read it: the class EuroSignProbe and the function main, doing all the work.

Watch out for

  • Every symbol it touches is a language built-in — nothing to fetch.

Using it

Signature: public static void main(String[] args)

The file announces its steps in the output: strict encode threw:, lenient encode:, bytes written:.

Key statements

String round = new String(bytes.array(), 0, bytes.remaining(), latin1);
String text = "café € 99"; // '€' 不在 ISO-8859-1 里,是 unmappable 字符
// 默认动作是 REPORT:遇到不可映射字符直接抛异常,编码中断
try {
    latin1.newEncoder().encode(CharBuffer.wrap(text));
} catch (Exception e) {
    System.out.println("strict encode threw: " + e.getClass().getSimpleName());
}
ByteBuffer bytes = lenient.encode(CharBuffer.wrap(text));

Interactive Tools for This Topic

FAQ

What does CharsetEncoder Replaces Unmappable Input print when run?
Running the file directly is enough — expect labeled output lines such as `strict encode threw:`, `lenient encode:`, `bytes written:`.