Android/Java 获取一个byte[]的真实编码,用于解决乱码问题

原创
2018/11/18 13:49
阅读数 2.2K

来源地址:https://blog.csdn.net/qq_31384551/article/details/81627840

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

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

组件叫,juniversalchardet

jar包下载地址:http://maven.outofmemory.cn/com.googlecode.juniversalchardet/juniversalchardet/1.0.3/

maven引用:

        <dependency>
            <groupId>com.googlecode.juniversalchardet</groupId>
            <artifactId>juniversalchardet</artifactId>
            <version>1.0.3</version>
        </dependency>

调用代码:

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;
}

 

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
1 收藏
0
分享
返回顶部
顶部