使用第三方库cpdetector来判断文件的编码方式

来源:互联网 发布:淘宝售假申诉成功 编辑:程序博客网 时间:2024/06/05 06:01

在android中读取文本文件时如果不考虑文件的编码方式直接读取的话很容易出现乱码。cpdetector库可以在读取前判断文件的编码方式从而在读取文件时可以将得到的文件编码方式charset直接进行设置,就不会出现乱码:

public static String getFileCharset(String filePath) {        //通过文件路径来获得文件        File file = new File(filePath);        Charset charset = null;        try {            // 获取原始文件编码            CodepageDetectorProxy detector = CodepageDetectorProxy.getInstance();            detector.add(JChardetFacade.getInstance());            charset = detector.detectCodepage(file.toURL());        } catch (IOException e) {            e.printStackTrace();        }        return charset.name();    }

最后将获得到的charset设置到inputstreamReader中去

String charset = charset.name();InputStreamReader isr = new InputStreamReader(fis, charset);

cpdetector 下载地址:[http://sourceforge.net/projects/cpdetector/]

0 0
原创粉丝点击