如何使用java将UTF16(表情符号)转换为HTML实体(十六进制)

时间:2016-01-27 08:35:49

标签: java html jsp emoji emoticons

How to convert UTF16 (emoji) to HTML Entity (hex) using java


I have the string from DB like this "\uD83D\uDE02". 
I try to display this unicode emoji, it displays as ��. 
I search in google to convert UTF16 to Html hex code. But i didnt get any solution. Please help me

我将把这个unicode显示给Emoji smily icon

2 个答案:

答案 0 :(得分:3)

您可以使用emoji4j库。

例如:

String line = "Hi , i am fine \uD83D\uDE02 \uD83D\uDE02, how r u ?";

EmojiUtils.hexHtmlify(line); //Hi , i am fine 😂 😂, how r u ?

答案 1 :(得分:2)

虽然字符串似乎包含两个Unicode字符,但它已经是一个用UTF-16编码的字符,这就是Java字符串的工作方式。您可以使用String.codePointAt方法确定实际的UTF-16解码字符代码。这里的字符代码是0x1F602,它是Unicode 'FACE WITH TEARS OF JOY'

将字符写入HTML:

选项1:生成HTML转义实体

String str="\uD83D\uDE02";
FileWriter w=new FileWriter("c:\\temp\\emoji.html");
w.write("<html><body>");
w.write("&#x"+Long.toHexString(str.codePointAt(0))+";");
w.write("</body></html>");
w.close();

这会产生

<html><body>&#x1f602;</body></html>

选项2:使用一些支持Unicode的HTML编码,例如UTF-8

String str="\uD83D\uDE02";
OutputStreamWriter w=new OutputStreamWriter(new FileOutputStream("c:\\temp\\emoji.html"),"UTF-8");
w.write("<html>\n<head><meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\"></head>\n<body>");
w.write(str);
w.write("</body></html>");
w.close();

这会产生

<html>
<head><meta http-equiv="content-type" content="text/html; charset=utf-8"></head>
<body>рџ‚</body></html>

这是用UTF-8编码的同一张快乐脸。