实现说明
真正干活的是类 EuroSignProbe和函数 main,其余都是接线。
使用要点
- 演示输出是带标签的(
strict encode threw:、lenient encode:、bytes written:),每个操作都会留下自己的一行标注。
常见问题
运行「CharsetEncoder 替换不可映射字符」会打印什么?
不用做任何设置,直接把文件跑完——输出里的 strict encode threw:、lenient encode:、bytes written: 标签标明各步骤。
核心语句
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));
代码示例
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());
}
}