在 Java 中显示 UTF-8 表情符号

Displaying UTF-8 Emoji in Java

假设我有(恶魔)表情符号。

在4字节的UTF-8中,它是这样表示的:\u00f0\u009f\u0098\u0088

然而,在Java中,它只会像这样正确打印:\ud83d\ude08

如何从第一个转换为第二个?

更新 2

MNEMO 的回答要简单得多,并且回答了我的问题,所以最好采用他的解决方案。

更新

感谢 Basil Bourque 的撰写。非常有趣。

我在这里找到了一个很好的参考:https://github.com/pRizz/Unicode-Converter/blob/master/conversionfunctions.js(特别是 convertUTF82Char() 函数)。

对于以后路过这里的人来说,这是 Java 中的样子:

public static String fromCharCode(int n) {
    char c = (char)n;
    return Character.toString(c);
}

public static String decToChar(int n) {
    // converts a single string representing a decimal number to a character
    // note that no checking is performed to ensure that this is just a hex number, eg. no spaces etc
    // dec: string, the dec codepoint to be converted
    String result = "";
    if (n <= 0xFFFF) {
        result += fromCharCode(n);
    } else if (n <= 0x10FFFF) {
        n -= 0x10000;
        result += fromCharCode(0xD800 | (n >> 10)) + fromCharCode(0xDC00 | (n & 0x3FF));
    } else {
        result += "dec2char error: Code point out of range: " + decToHex(n);
    }

    return result;
}

public static String decToHex(int n) {
    return Integer.toHexString(n).toUpperCase();
}

public static String convertUTF8_toChar(String str) {
    // converts to characters a sequence of space-separated hex numbers representing bytes in utf8
    // str: string, the sequence to be converted
    var outputString = "";
    var counter = 0;
    var n = 0;

    // remove leading and trailing spaces
    str = str.replaceAll("/^\s+/", "");
    str = str.replaceAll("/\s+$/", "");
    if (str.length() == 0) {
        return "";
    }

    str = str.replaceAll("/\s+/g", " ");

    var listArray = str.split(" ");
    for (var i = 0; i < listArray.length; i++) {
        int b = parseInt(listArray[i], 16); // alert('b:'+dec2hex(b));
        switch (counter) {
            case 0:
                if (0 <= b && b <= 0x7F) { // 0xxxxxxx
                    outputString += decToChar(b);
                } else if (0xC0 <= b && b <= 0xDF) { // 110xxxxx
                    counter = 1;
                    n = b & 0x1F;
                } else if (0xE0 <= b && b <= 0xEF) { // 1110xxxx
                    counter = 2;
                    n = b & 0xF;
                } else if (0xF0 <= b && b <= 0xF7) { // 11110xxx
                    counter = 3;
                    n = b & 0x7;
                } else {
                    outputString += "convertUTF82Char: error1 " + decToHex(b) + "! ";
                }
                break;
            case 1:
                if (b < 0x80 || b > 0xBF) {
                    outputString += "convertUTF82Char: error2 " + decToHex(b) + "! ";
                }
                counter--;
                outputString += decToChar((n << 6) | (b - 0x80));
                n = 0;
                break;
            case 2:
            case 3:
                if (b < 0x80 || b > 0xBF) {
                    outputString += "convertUTF82Char: error3 " + decToHex(b) + "! ";
                }
                n = (n << 6) | (b - 0x80);
                counter--;
                break;
        }
    }

    return outputString.replaceAll("/ $/", "");
}

几乎是一对一的副本,但它实现了我的目标。

SMILING FACE WITH HORNS character () is assigned to code point 128,520 decimal (1F608 hexadecimal) in Unicode.

您可以选择如何用一系列 octets 表示该数字。

  • UTF-8 是一种使用 1-4 个八位字节表示具有可变长度的数字的方法。
    • UTF-8 正在成为许多领域的主导编码。
    • Java 源代码文件通常以 UTF-8 编写,根据我的经验,正如所讨论的 here.
  • UTF-16 是另一种方式,也是可变长度的,但使用 2 个八位字节或 4 个八位字节。
    • 内部 Java 语言 uses UTF-16
    • UTF-8 通常优于 UTF-16,如 here.
    • 所述

在大多数文本编辑器中,您只需将单个字符 </code> 粘贴到源代码中即可。写入 UTF-8 文件时,编辑器将创建必要的八位字节系列。 </p> <p>将此字符写入文本文件或序列化为八位字节流时​​,您可以选择使用 UTF-8 或 UTF-16。参见:</p> <ul> <li><a href=""><em>How to write a UTF-8 file with Java?</em></a></li> <li><a href=""><em>How to Open File in UTF-8 and Write in Another File in UTF-16</em></a></li> </ul> <p>以下是几个试验。您可以使用 <a href="https://en.wikipedia.org/wiki/Hex_editor" rel="nofollow noreferrer">hex editor</a> 检查生成的文件以查看八位字节。 </p> <h2>UTF-8</h2> <p>此代码生成 UTF-8 编码的文件。我们找到四个八位字节,十六进制值 F0 9F 98 88,十进制值 240 159 152 136。</p> <p>您可以在 <a href="https://docs.oracle.com/javase/tutorial/essential/io/file.html" rel="nofollow noreferrer">Oracle Java Tutorial</a> 中找到此代码的讨论。 </p> <p>注意我们如何为文件指定编码,<a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/nio/charset/StandardCharsets.html#UTF_8" rel="nofollow noreferrer"><code>StandardCharsets.UTF_8

Path file = Paths.get( "/Users/basilbourque/devil_utf-8.txt" );
Charset charset = StandardCharsets.UTF_8;
String s = "";
try ( BufferedWriter writer = Files.newBufferedWriter( file , charset ) )
{
    writer.write( s , 0 , s.length() );
}
catch ( IOException e )
{
    e.printStackTrace();
}

UTF-16

此代码生成 UTF-16 编码的文件。我们找到 6 个八位字节,4 个八位字节用于我们的单个字符,加上 2 个八位字节的前缀用于 BOM (FE FF)。我们的四个十进制八位字节是 216 061 222 008,十六进制是 D8 3D DE 08。

与上面相同的代码,但我们切换了 Charset to StandardCharsets.UTF_16

Path file = Paths.get( "/Users/basilbourque/devil_utf-16.txt" );
Charset charset = StandardCharsets.UTF_16;
String s = "";
try ( BufferedWriter writer = Files.newBufferedWriter( file , charset ) )
{
    writer.write( s , 0 , s.length() );
}
catch ( IOException e )
{
    e.printStackTrace();
}

关于 Unicode 和编码

要了解 Unicode 和编码的基础知识,请阅读 post、The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)

好吧,这完全没有必要添加,但是在您了解所有字符编码系统和 Unicode 概念之后,以下代码可能对您有用。

byte[] a = { (byte)0xf0, (byte)0x9f, (byte)0x98, (byte)0x88 };
String s = new String(a,"UTF-8");
byte[] b = s.getBytes("UTF-16BE");
for ( byte c : b ) { System.out.printf("%02x ",c); }