假设我将Java字符数组(char[]
)实例编码为bytes:
这会始终创建有效的UTF-16BE编码吗?如果不是,哪些代码点将导致无效编码?
此问题与this question about the Java char type和this question about the internal representation of Java strings非常相关。
答案 0 :(得分:8)
没有。您可以创建包含任何所需16位值的char
实例 - 没有任何东西可以将它们限制为有效的UTF-16代码单元,也不会将它们的数组限制为有效的UTF-16序列。即使String
也不要求其数据有效UTF-16:
char data[] = {'\uD800', 'b', 'c'}; // Unpaired lead surrogate
String str = new String(data);
有效UTF-16数据的要求在Unicode标准的Chapter 3中列出(基本上,所有内容都必须是Unicode标量值,并且所有代理必须正确配对)。您可以测试char
数组是否是有效的UTF-16序列,并使用CharsetEncoder
将其转换为UTF-16BE(或LE)字节序列:
CharsetEncoder encoder = Charset.forName("UTF-16BE").newEncoder();
ByteBuffer bytes = encoder.encode(CharBuffer.wrap(data)); // throws MalformedInputException
(如果你有字节的话,同样使用CharsetDecoder
。)