在Java中将int(字节)转换为单字符字符串的最简单方法

Kev*_*sen 1 java string byte casting character

我有一个表示有效UTF-8字符的int(->字节),并且我想在中打印该单个字符System.out.println

我知道以下两种将表示UTF-8字节的int转换为单字符字符串的方法:

int myByte = ...; // For example 67

String sMyByte = String.valueOf((char)((byte)myByte & 0xFF)); // 67 will become "C"

String sMyByte = new String(new byte[]{ (byte)myByte }, StandardCharsets.UTF_8); // 67 will become "C"
Run Code Online (Sandbox Code Playgroud)

两者似乎有点长/不可读,我想知道是否存在一种更简便的方法来将表示UTF-8字节的int转换为单字符字符串。如果没有,我可能会使用上面两个中的第一个。

fge*_*fge 5

你不应该调用你的int myByte; 它实际上是Unicode代码点。

最简单的方法是使用Character.toChars()

final String s = new String(Character.toChars(theCodePoint));
Run Code Online (Sandbox Code Playgroud)

它将处理每个代码点;之后,这取决于您使用的字体是否有针对该代码点的标志符号!

另请注意,UTF-8是字符编码。实际上,您没有UTF-8字符之类的东西。

如需进一步查询,请查看CharsetEncoderCharsetDecoder类。