Java获取文本文件编码

网上找过几种获取文件编码的方式,发现这种方法是最准确的。

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

猜你喜欢

转载自blog.csdn.net/xqnode/article/details/85065006
今日推荐