Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 中如何判斷文字檔案的編碼

編輯:關於 Android 程式設計

處理使用者匯入的檔案時,編碼判斷幾乎是必經之路。以下整理三種實作方式,從手寫規則到開源庫,各有適用場景。

方法一:利用 Windows 文字檔的 BOM 特徵

在 Windows 環境下存出的 Unicode、Unicode big endian 與 UTF-8 文字檔,開頭會多出幾個位元組作為識別碼(BOM):FF FE 代表 Unicode(UTF-16LE)、FE FF 代表 Unicode big endian(UTF-16BE)、EF BB BF 代表 UTF-8。

public static String getCharset(File file) {
    String charset = "GBK";
    byte[] first3Bytes = new byte[3];
    try {
        boolean checked = false;
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
        bis.mark(0);
        int read = bis.read(first3Bytes, 0, 3);
        if (read == -1) return charset;

        if (first3Bytes[0] == (byte) 0xFF && first3Bytes[1] == (byte) 0xFE) {
            charset = "UTF-16LE";
            checked = true;
        } else if (first3Bytes[0] == (byte) 0xFE && first3Bytes[1] == (byte) 0xFF) {
            charset = "UTF-16BE";
            checked = true;
        } else if (first3Bytes[0] == (byte) 0xEF && first3Bytes[1] == (byte) 0xBB
                   && first3Bytes[2] == (byte) 0xBF) {
            charset = "UTF-8";
            checked = true;
        }

        bis.reset();
        if (!checked) {
            // 沒有 BOM,改用 UTF-8 多-byte 序列的字位模式來猜
            int loc = 0;
            while ((read = bis.read()) != -1) {
                loc++;
                if (read >= 0xF0) break;
                if (0x80 <= read && read <= 0xBF) break;
                if (0xC0 <= read && read <= 0xDF) {
                    read = bis.read();
                    if (0x80 <= read && read <= 0xBF) continue;  // 雙位元組
                    else break;
                } else if (0xE0 <= read && read <= 0xEF) {
                    read = bis.read();
                    if (0x80 <= read && read <= 0xBF) {
                        read = bis.read();
                        if (0x80 <= read && read <= 0xBF) {
                            charset = "UTF-8";
                            break;                                  // 三位元組
                        } else break;
                    } else break;
                }
            }
        }
        bis.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return charset;
}

缺點:這種做法依賴 BOM,而 Linux 環境存出的檔案通常沒有 BOM,偵測就會失效。此外,純 ASCII 內容無法與 UTF-8 區分,只能一律歸類為預設值。

方法二:開源專案 JCharDet

JCharDet 是 Mozilla 自動字符集偵測演算法的 Java 移植版,官方網站為 https://jchardet.sourceforge.net/ 。使用方式如下:

package org.mozilla.intl.chardet;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * 借助 JCharDet 取得檔案字符集
 */
public class FileCharsetDetector {

    private boolean found = false;
    /** 若完全匹配某字符集演算法,此屬性保存該字符集名稱;否則為 null */
    private String encoding = null;

    /**
     * 傳入 File 物件,檢查檔案編碼
     * @return 檔案編碼,若無法判定則回傳 null
     */
    public String guestFileEncoding(File file) throws IOException {
        return guestFileEncoding(file, new nsDetector());
    }

    /**
     * @param languageHint 語言提示:1 日文、2 中文、3 簡體中文、
     *                       4 繁體中文、5 韓文、6 未知(預設)
     */
    public String guestFileEncoding(File file, int languageHint) throws IOException {
        return guestFileEncoding(file, new nsDetector(languageHint));
    }

    public String guestFileEncoding(String path) throws IOException {
        return guestFileEncoding(new File(path));
    }

    public String guestFileEncoding(String path, int languageHint) throws IOException {
        return guestFileEncoding(new File(path), languageHint);
    }

    private String guestFileEncoding(File file, nsDetector det) throws IOException {
        // 註冊 observer,比對成功時 Notify() 會被呼叫
        det.Init(new nsICharsetDetectionObserver() {
            public void Notify(String charset) {
                found = true;
                encoding = charset;
            }
        });

        BufferedInputStream imp = new BufferedInputStream(new FileInputStream(file));
        byte[] buf = new byte[1024];
        int len;
        boolean done = false;
        boolean isAscii = true;

        while ((len = imp.read(buf, 0, buf.length)) != -1) {
            // 先確認是否為純 ASCII
            if (isAscii) isAscii = det.isAscii(buf, len);
            // 非 ASCII 且尚未判定完成時才繼續分析
            if (!isAscii && !done) done = det.DoIt(buf, len, false);
        }
        det.DataEnd();

        if (isAscii) {
            encoding = "ASCII";
            found = true;
        }

        if (!found) {
            String prob[] = det.getProbableCharsets();
            if (prob.length > 0) {
                encoding = prob[0];   // 取第一個可能的編碼
            } else {
                return null;
            }
        }
        return encoding;
    }
}

語言提示參數可以顯著提升判斷的準確率——知道內容大概是哪個語系,演算法的候選集就能大幅縮小。

方法三:juniversalchardet(推薦)

專案網址:https://code.google.com/p/juniversalchardet/ 。使用方式更簡潔:

public static String getFileIncode(File file) {
    if (!file.exists()) {
        return null;
    }
    byte[] buf = new byte[4096];
    try (FileInputStream fis = new FileInputStream(file)) {
        // (1) 建立偵測器
        UniversalDetector detector = new UniversalDetector(null);

        // (2) 逐段餵入資料
        int nread;
        while ((nread = fis.read(buf)) > 0 && !detector.isDone()) {
            detector.handleData(buf, 0, nread);
        }

        // (3) 通知資料結束
        detector.dataEnd();

        // (4) 取得結果
        String encoding = detector.getDetectedCharset();
        if (encoding != null) {
            System.out.println("Detected encoding = " + encoding);
        } else {
            System.out.println("No encoding detected.");
        }

        // (5) 重置,以便重複使用
        detector.reset();
        return encoding;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

其中 detector.isDone() 讓迴圈能在演算法確信結果後提早結束,不必讀完整個檔案,這是它在速度上優於逐位元組比對的關鍵。

引入方式

把 jar 放入 libs 資料夾,選取該 jar → 右鍵 → Build Path → Add to Build Path 即可。

選擇建議

第三個方法(juniversalchardet)比第二個更快、維護也更活躍,因此優先推薦。方法一則適合「已知對方一定來自 Windows、且檔案很小」這類單純場景。要注意的是,任何編碼偵測本質上都是機率判斷,若對正確性要求極高,最穩妥的做法還是在檔案格式中明確攜帶編碼資訊。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved