Java獲取文字檔案編碼
阿新 • • 發佈:2018-12-19
網上找過幾種獲取檔案編碼的方式,發現這種方法是最準確的。
jar包下載:
https://sourceforge.net/projects/cpdetector/?source=typ_redirect
cpdetector一個可以自動檢測文字編碼格式的專案
detector按照“誰最先返回非空的探測結果,就以該結果為準”的原則返回探測到的 字符集編碼。
使用需要用到三個第三方JAR包:antlr.jar、chardet.jar和cpdetector.jar
cpDetector是基於統計學原理的,不保證完全正確。
下面是程式碼,可以直接copy試一下便知:
public static String getFileEncode(String filePath) {
String charsetName = "";
try {
File file = new File(filePath);
CodepageDetectorProxy detector = CodepageDetectorProxy.getInstance();
detector.add(new ParsingDetector(false));
//新增三種編碼格式
detector. add(JChardetFacade.getInstance());
detector.add(ASCIIDetector.getInstance());
detector.add(UnicodeDetector.getInstance());
java.nio.charset.Charset charset = null;
charset = detector.detectCodepage(file.toURI().toURL());
if (charset != null) {
charsetName = charset.name();
} else {
charsetName = "UTF-8";
}
} catch (Exception ex) {
ex.printStackTrace();
}
return charsetName;
}
本文轉載自https://blog.csdn.net/wuseyukui/article/details/45799207