【问题标题】:JAVA Code To Identify A String With UTF-8 data用 UTF-8 数据识别字符串的 JAVA 代码
【发布时间】:2018-03-24 14:22:45
【问题描述】:

我正在尝试标准化一组数据。有些名称是 UTF-8 编码的,有些则不是。我需要在 JAVA 中做的是检测名称是 UTF 编码还是不使用某种形式的条件逻辑,以便我可以正确翻译每一行。

String s1 = "José Flores";
String s1 = "José Flores";

IF [condition] (identify UTF-8)
    byte[] utf8Bytes = s1.getBytes("ISO-8859-1");
    String s2 = new String(utf8Bytes,"UTF-8");
ELSE
    String s2 = s1;

【问题讨论】:

    标签: java utf-8 8-bit


    【解决方案1】:

    juniversalchardet的帮助下,可以得到编码,然后进行条件运算。这可以帮助您获得编码类型。

    public static String guessEncoding(byte[] bytes) {
    String DEFAULT_ENCODING = "UTF-8";
    org.mozilla.universalchardet.UniversalDetector detector =
        new org.mozilla.universalchardet.UniversalDetector(null);
    detector.handleData(bytes, 0, bytes.length);
    detector.dataEnd();
    String encoding = detector.getDetectedCharset();
    detector.reset();
    if (encoding == null) {
        encoding = DEFAULT_ENCODING;
      }
     return encoding;
    }
    

    这需要juniversalchardet-1.0.3.jar,另外here是一些信息

    【讨论】:

      猜你喜欢
      • 2010-09-27
      • 1970-01-01
      • 1970-01-01
      • 2012-11-10
      • 1970-01-01
      • 2023-03-27
      • 2020-03-24
      • 2011-08-16
      • 1970-01-01
      相关资源
      最近更新 更多