jChardet探测文件字符编码

简介: package test;import java.io.BufferedInputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import org.mozilla.intl.char
package test;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.mozilla.intl.chardet.nsDetector;
import org.mozilla.intl.chardet.nsICharsetDetectionObserver;
// jChardet 火狐所用字符编码检测算法
public class FileCharsetDetector {
    private boolean found = false;
    private String encoding = null;

    public static void main(String[] argv) throws Exception {
        File file1 = new File("C:\\Users\\Administrator\\Desktop\\VideoViewDemo\\VideoViewDemo\\src\\org\\apache\\android\\media\\AudioPlayer.java");
        
        System.out.println("文件编码:" + new FileCharsetDetector().guessFileEncoding(file1));
    }

    /**
     * 传入一个文件(File)对象,检查文件编码
     * 
     * @param file
     *            File对象实例
     * @return 文件编码,若无,则返回null
     * @throws FileNotFoundException
     * @throws IOException
     */
    public String guessFileEncoding(File file) throws FileNotFoundException, IOException {
        return guessFileEncoding(file, new nsDetector());
    }

    /**
     * <pre>
     * 获取文件的编码
     * @param file
     *            File对象实例
     * @param languageHint
     *            语言提示区域代码 @see #nsPSMDetector ,取值如下:
     *             1 : Japanese
     *             2 : Chinese
     *             3 : Simplified Chinese
     *             4 : Traditional Chinese
     *             5 : Korean
     *             6 : Dont know(default)
     * </pre>
     * 
     * @return 文件编码,eg:UTF-8,GBK,GB2312形式(不确定的时候,返回可能的字符编码序列);若无,则返回null
     * @throws FileNotFoundException
     * @throws IOException
     */
    public String guessFileEncoding(File file, int languageHint) throws FileNotFoundException, IOException {
        return guessFileEncoding(file, new nsDetector(languageHint));
    }

    /**
     * 获取文件的编码
     * 
     * @param file
     * @param det
     * @return
     * @throws FileNotFoundException
     * @throws IOException
     */
    private String guessFileEncoding(File file, nsDetector det) throws FileNotFoundException, IOException {
        // Set an observer...
        // The Notify() will be called when a matching charset is found.
        det.Init(new nsICharsetDetectionObserver() {
            public void Notify(String charset) {
                encoding = charset;
                found = true;
            }
        });

        BufferedInputStream imp = new BufferedInputStream(new FileInputStream(file));
        byte[] buf = new byte[1024];
        int len;
        boolean done = false;
        boolean isAscii = false;

        while ((len = imp.read(buf, 0, buf.length)) != -1) {
            // Check if the stream is only ascii.
            isAscii = det.isAscii(buf, len);
            if (isAscii) {
                break;
            }
            // DoIt if non-ascii and not done yet.
            done = det.DoIt(buf, len, false);
            if (done) {
                break;
            }
        }
        imp.close();
        det.DataEnd();

        if (isAscii) {
            encoding = "ASCII";
            found = true;
        }

        if (!found) {
            String[] prob = det.getProbableCharsets();
            //这里将可能的字符集组合起来返回
            for (int i = 0; i < prob.length; i++) {
                if (i == 0) {
                    encoding = prob[i];
                } else {
                    encoding += "," + prob[i];
                }
            }

            if (prob.length > 0) {
                // 在没有发现情况下,也可以只取第一个可能的编码,这里返回的是一个可能的序列
                return encoding;
            } else {
                return null;
            }
        }
        return encoding;
    }
}


参考文章:

http://www.cnblogs.com/yejg1212/p/3402322.html


本文出自 “点滴积累” 博客,请务必保留此出处http://tianxingzhe.blog.51cto.com/3390077/1774032

目录
相关文章
|
SQL Oracle 关系型数据库
java往oracle存clob类型的值时,字符长度过长怎么办?
java往oracle存clob类型的值时,字符长度过长怎么办?
1236 1
|
机器学习/深度学习 自然语言处理 算法
【数据挖掘】金山办公2020校招大数据和机器学习算法笔试题
金山办公2020校招大数据和机器学习算法笔试题的解析,涵盖了编程、数据结构、正则表达式、机器学习等多个领域的题目和答案。
320 10
|
供应链 数据挖掘 API
探秘淘宝商品SKU信息API接口
在电子商务中,SKU(库存量单位)用于区分商品的不同规格、颜色、尺寸等属性,是精细化管理的基础。本文深入探讨淘宝商品SKU信息API接口,介绍其功能特点、使用方法及应用场景,并提供Python代码示例。该API支持实时更新、多维度筛选,帮助开发者获取全面的SKU信息,优化库存管理、订单处理和销售数据分析,提升运营效率与市场竞争力。
970 1
|
Serverless BI Python
Python中的for循环和range()函数用法详解
Python中的for循环和range()函数用法详解
|
Dubbo Java 应用服务中间件
源码分析Dubbo 泛化调用与泛化实现原理
源码分析Dubbo 泛化调用与泛化实现原理
源码分析Dubbo 泛化调用与泛化实现原理
|
存储 消息中间件 算法
深入解析OpenStack Cinder:块存储服务详解
本文介绍了OpenStack及其块存储服务Cinder。OpenStack是一个开源云计算管理平台,提供基础设施即服务(IaaS),核心服务包括计算、网络、存储等。Cinder主要用于为虚拟机提供持久性块存储,具备多种功能,如卷操作、备份、快照及与实例的交互等。此外,还详细介绍了Cinder的工作流程、命令行操作及不同存储插件的使用。
1990 8
|
NoSQL 数据处理 调度
【Redis技术专区】「原理分析」探讨Redis6.0为何需要启用多线程
在Redis 6.0版本中,引入了多线程技术,这是为了进一步提高Redis的性能和并发处理能力。通过启用多线程,Redis能够同时处理多个客户端请求,有效地利用多核处理器资源,提高系统的吞吐量和响应速度。
784 1
【Redis技术专区】「原理分析」探讨Redis6.0为何需要启用多线程
DC-MOTOR直流电机的simulink建模与性能仿真
使用MATLAB2022a和Simulink构建的DC电机模型进行仿真,展示了电机在240V电枢电压和150V励磁绕组输入下的性能。仿真输出包括转速、电枢及励磁电流、电磁转矩随时间的变化。结果以图像形式呈现,揭示了电机在洛伦兹力和电磁感应定律作用下的工作原理,通过电流与磁场的交互转换电能为机械能。直流电机借助换向器维持稳定的电磁转矩,并遵循法拉第电磁感应定律和楞次定律。
|
安全 Java
java.security.InvalidKeyException: Illegal key size
java.security.InvalidKeyException: Illegal key size
448 0