2015-02-24 13:50

[Java] 取得檔案編碼格式

使用 Mozilla juniversalchardet 套件

import java.io.FileInputStream;
import org.mozilla.universalchardet.UniversalDetector;

public class ReadFileCharset {

    public static void main(String[] args) throws Exception {

        /* 讀取檔案 */
        FileInputStream fis = new FileInputStream("input.txt");

        /* 建立分析器 */
        UniversalDetector detector = new UniversalDetector(null);

        int nread;
        byte[] buf = new byte[4096];
        while ((nread = fis.read(buf)) > 0 && !detector.isDone()) {
            /* 分析資料 */
            detector.handleData(buf, 0, nread);
        }
        fis.close();

        detector.dataEnd();

        /* 取得編碼格式 */
        String encode = detector.getDetectedCharset();
        System.out.println(encode);
    }
}

0 回應: