繁体   English   中英

JAVA代码以UTF-8数据标识字符串

[英]JAVA Code To Identify A String With UTF-8 data

我正在尝试标准化一组数据。 其中一些名称是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;

借助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, 也是一些信息

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM