【问题标题】:How to decode emoji (unicode) in HBase using Java API?如何使用 Java API 在 HBase 中解码表情符号(unicode)?
【发布时间】:2017-03-31 09:57:59
【问题描述】:

在我的 HBase 表中,有一些编码的表情符号,如 \xF0\x9F\x8C\x8F 和 \xE2\x9A\xBE。我正在尝试使用 Bytes.toString() 来解码它们。但是,这种方法使用 utf-8,它只能解码像 \xE2\x9A\xBE 这样的三字节代码,而像 \xF0\x9F\x8C\x8F 这样的四字节代码似乎是一个问号(见下文)。那么如何将四个字节的代码解码为表情符号并打印出来呢?有人有想法吗?提前致谢!

例子:

结果应该是:

但我得到了

很抱歉,我忘记提及我正在使用 servlet 查询 HBase 并将内容写入响应。

【问题讨论】:

  • 您确定编码是 UTF-8 吗?如果是这样,那么您的转换是正确的,但您的操作系统可能不知道如何表示您的表情符号背后的字符
  • new String(theBytes, theCharset)?
  • 你问的是我使用的方法 - Bytes.toString() 吗?官方文档显示此方法使用utf-8作为默认编码,无法更改其编码....我可以查看hbase,发现表情符号以unicode编码存储,如\xF0\x9F \x8C\x8F.

标签: java database unicode encoding hbase


【解决方案1】:

当我读取包含以下字符“?”(F09F8C8F 或 U+1F30F)的文件并且它有一个指示 UTF-8 编码的 BOM 时,我通过使用正确地将其转换为 UTF-8

byte[] encoded = Files.readAllBytes(selectedFile.toPath());
String fileContents = new String(encoded, StandardCharsets.UTF_8);

生成的字符串已正确转换并正确显示在我的 Java Swing 应用程序中。但是,如果我将相同的字符串打印到控制台,我会得到一个带框的问号而不是符号。所以字符被正确转换,但只是你的输出把它弄乱了。

要重新创建它,您可以使用它:

public static void main(String[] args) throws Exception {
  byte[] encoded = { (byte) 0xF0, (byte) 0x9F, (byte) 0x8C, (byte) 0x8F };
  String convertedstring = new String(encoded, StandardCharsets.UTF_8);

  System.out.println("convertedstring: " + convertedstring);

  JDialog dialog = new JDialog();
  dialog.setSize(300, 100);
  dialog.setLocationRelativeTo(null);
  dialog.setTitle("encoding-test");
  dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
  JLabel label = new JLabel("convertedstring: " + convertedstring);
  dialog.add(label);

  dialog.setVisible(true);
}

控制台输出

JDialog 输出

您可能还想看看Default character encoding for java console outputJava, UTF-8, and Windows console

【讨论】:

  • 感谢您的回复。但是我很抱歉我忘了提到我正在使用 servlet 来查询 HBase 并将内容写入响应。
  • @DiLuo 你能看到我回复中的表情符号吗?如果不是,您可能想更新您的浏览器。还要检查您的响应具有哪种 HTML 内容类型
  • 我在您的代码中看不到表情符号,但我将标头的内容类型和编码设置为 UTF-16,现在我可以在响应中看到表情符号。谢谢你的灵感!
猜你喜欢
  • 2020-02-29
  • 1970-01-01
  • 2021-06-01
  • 2017-09-26
  • 2017-08-24
  • 2019-12-07
  • 1970-01-01
  • 1970-01-01
  • 2014-09-24
相关资源
最近更新 更多