Android/Java 獲取一個byte[]的真實編碼,用於解決亂碼問題

來源地址: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;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章