现在的位置: 首页 > 综合 > 正文

java怎么判断byte[]的原字符串的编码?

2018年04月10日 ⁄ 综合 ⁄ 共 599字 ⁄ 字号 评论关闭

一个byte数组,byte[] buf,是由一个字符串转换来的,如何判断字符串使用的是什么编码?

Mozilla的一个组件提供了相应功能:

组件叫,juniversalchardet,下载地址:https://juniversalchardet.googlecode.com/files/juniversalchardet-1.0.3.jar

也可以到组件官网下载最新版本:https://code.google.com/p/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;
}

抱歉!评论已关闭.