网上找过几种获取文件编码的方式,发现这种方法是最准确的。
jar包下载:
https://sourceforge.net/projects/cpdetector/?source=typ_redirect
cpdetector一个可以自动检测文本编码格式的项目
detector按照“谁最先返回非空的探测结果,就以该结果为准”的原则返回探测到的 字符集编码。
使用需要用到三个第三方JAR包:antlr.jar、chardet.jar和cpdetector.jar
下面是代码,可以直接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.youkuaiyun.com/wuseyukui/article/details/45799207