前段时间,在学习lucene的时候,遇到了读取txt文档遇到编码错误的问题。学了几个解决方案,大部分是将文件转十六进制(可以使用UE的Ctrl+H来查看),读取开头的四个标志位来判断。可是总有些文本文件无法识别(我遇到的是部分使用UTF-8编码的文件),后来发现了JCharDet。JCharDet是mozilla(就是firefox那家)的编码识别算法的Java实现,算了,这里是官网,自己看吧。

上代码:

package com.zhyea.util;

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获取文件字符集
*
* @author robin
*
*/
public class FileCharsetDetector { /**
* 字符集名称
*/
private static String encoding; /**
* 字符集是否已检测到
*/
private static boolean found; private static nsDetector detector; private static nsICharsetDetectionObserver observer; /**
* 适应语言枚举
* @author robin
*
*/
enum Language{
Japanese(1),
Chinese(2),
SimplifiedChinese(3),
TraditionalChinese(4),
Korean(5),
DontKnow(6); private int hint; Language(int hint){
this.hint = hint;
} public int getHint(){
return this.hint;
}
} /**
* 传入一个文件(File)对象,检查文件编码
*
* @param file
* File对象实例
* @return 文件编码,若无,则返回null
* @throws FileNotFoundException
* @throws IOException
*/
public static String checkEncoding(File file) throws FileNotFoundException,
IOException {
return checkEncoding(file, getNsdetector());
} /**
* 获取文件的编码
*
* @param file
* File对象实例
* @param language
* 语言
* @return 文件编码
* @throws FileNotFoundException
* @throws IOException
*/
public static String checkEncoding(File file, Language lang)
throws FileNotFoundException, IOException {
return checkEncoding(file, new nsDetector(lang.getHint()));
} /**
* 获取文件的编码
*
* @param path
* 文件路径
* @return 文件编码,eg:UTF-8,GBK,GB2312形式,若无,则返回null
* @throws FileNotFoundException
* @throws IOException
*/
public static String checkEncoding(String path) throws FileNotFoundException,
IOException {
return checkEncoding(new File(path));
} /**
* 获取文件的编码
*
* @param path
* 文件路径
* @param language
* 语言
* @return
* @throws FileNotFoundException
* @throws IOException
*/
public static String checkEncoding(String path, Language lang)
throws FileNotFoundException, IOException {
return checkEncoding(new File(path), lang);
} /**
* 获取文件的编码
*
* @param file
* @param det
* @return
* @throws FileNotFoundException
* @throws IOException
*/
private static String checkEncoding(File file, nsDetector detector)
throws FileNotFoundException, IOException { detector.Init(getCharsetDetectionObserver()); if (isAscii(file, detector)) {
encoding = "ASCII";
found = true;
} if (!found) {
String prob[] = detector.getProbableCharsets();
if (prob.length > 0) {
encoding = prob[0];
} else {
return null;
}
} return encoding;
} /**
* 检查文件编码类型是否是ASCII型
* @param file
* 要检查编码的文件
* @param detector
* @return
* @throws IOException
*/
private static boolean isAscii(File file, nsDetector detector) throws IOException{
BufferedInputStream input = null;
try{
input = new BufferedInputStream(new FileInputStream(file)); byte[] buffer = new byte[1024];
int hasRead;
boolean done = false;
boolean isAscii = true; while ((hasRead=input.read(buffer)) != -1) {
if (isAscii)
isAscii = detector.isAscii(buffer, hasRead);
if (!isAscii && !done)
done = detector.DoIt(buffer, hasRead, false);
} return isAscii;
}finally{
detector.DataEnd();
if(null!=input)input.close();
}
} /**
* nsDetector单例创建
* @return
*/
private static nsDetector getNsdetector(){
if(null == detector){
detector = new nsDetector();
}
return detector;
} /**
* nsICharsetDetectionObserver 单例创建
* @return
*/
private static nsICharsetDetectionObserver getCharsetDetectionObserver(){
if(null==observer){
observer = new nsICharsetDetectionObserver() {
public void Notify(String charset) {
found = true;
encoding = charset;
}
};
}
return observer;
}
}

这个还存一个问题,就是识别Unicode编码的文件,会返回windows-1252。我使用windows-1252作为编码的时候会报错。

对了,再提供一个这个jar包下载的地址,官网有时会抽风,不能访问。

下载地址:http://download.csdn.net/detail/tianxiexingyun/8286849

就这样。

借助JCharDet获取文件字符集的更多相关文章

  1. Java如何获取文件编码格式

    1:简单判断是UTF-8或不是UTF-8,因为一般除了UTF-8之外就是GBK,所以就设置默认为GBK.  按照给定的字符集存储文件时,在文件的最开头的三个字节中就有可能存储着编码信息,所以,基本的原 ...

  2. JAVA中获取文件MD5值的四种方法

    JAVA中获取文件MD5值的四种方法其实都很类似,因为核心都是通过JAVA自带的MessageDigest类来实现.获取文件MD5值主要分为三个步骤,第一步获取文件的byte信息,第二步通过Messa ...

  3. java读取resource/通过文件名获取文件类型

    java读取resource java读取resource目录下文件的方法: 借助Guava库的Resource类 Resources.getResource("test.txt" ...

  4. Atitit.检测文本文件的编码 自动获取文件的中文编码

    Atitit.检测文本文件的编码 自动获取文件的中文编码 1 不能使用load来检测编码..1 2 使用convert来检测编码1 3 程序检测文本编码2 3.1 根据utf bom头2 3.2 检测 ...

  5. C++获取文件夹中所有文件

    获取文件夹中的文件,用到过很多次,每次用的时候都要去查下,很烦,所以想自己写下,当然,借鉴了很多其他大佬的博客 主要实现的函数,如下: void getFiles( string path, vect ...

  6. 获取文件的缩略图Thumbnail和通过 AQS - Advanced Query Syntax 搜索本地文件

    演示如何获取文件的缩略图 FileSystem/ThumbnailAccess.xaml <Page x:Class="XamlDemo.FileSystem.ThumbnailAcc ...

  7. FastDFS 通过文件名获取文件信息

    /** * 获取文件信息 * * param string group_name 文件所在的组名 * param string file_id 文件id(如: M00/09/BE/rBBZolgj6O ...

  8. c# .net获取文件夹下的所有文件(多层递归),并获取区间数据(Jsion,xml等数据)写出到处理文件,学习分享~

    static void Main(string[] args)        { string path = string.Format(@"C:\Users\Administrator\D ...

  9. java 获取文件列表,并按照文件名称排序

    需求:获取全部的日志文件,并按照文件名称倒序排列,把最新的文件放在最前1.获取全部的日志文件:(方法:public List<String> ergodic(File file,List& ...

随机推荐

  1. django模板继承

    可以将每个html公共的部分做成一个基本模板,其他模板继承这个基本模板,则会拥有基本模板的所有内容. views.py from django.shortcuts import render def ...

  2. AMQP 0.9.1和1.0协议差别以及rabbitmq支持情况

    RabbitMQ implements AMQP 1.0 via a plugin. However, AMQP 1.0 is a completely different protocol than ...

  3. DevExpress 数据绑定

  4. 前端基础小标签3 H5新标签

    第二部分H5的新标签一.<!-- mark标签             1.用于显示页面中需要重点关注的内容,就像看书需要用荧光笔划重点一样             2.浏览器通常会用黄色显示m ...

  5. 【Python025-字典】

    一.字典 1.创建和访问字典(字典是大括号表示,字典是映射类型) 语法类型:键:key,值:value,用冒号隔开 --- >>> dict1 = {'李宁':'一切皆有可能','耐 ...

  6. topcoder srm 545 div1

    problem1 link 这个可以贪心地从前向后构造.假设当前已经的字符串为$S$,对于一个字符$c$来说,设将$c$加到$S$后得到的新串为$S^{'}$.那么如果$X+Y+Z \ge minIn ...

  7. python第一阶段总结(1)

    python3第一阶段的总结 首先申明一下,本人是看网络课程“老男孩”过来写博客的,想把自己学到的东西分享一下.同时给老男孩打个广告,其教学水平真的挺好的.仅据我个人多年的学习评价. 好,接下来是我对 ...

  8. ODAC(V9.5.15) 学习笔记(九)TOraSQLMonitor

    名称 类型 说明 Active Boolean 激活SQL跟踪 DBMonitorOptions 将跟踪信息发送到dbMonitor工具软件的选择项 Host IP地址 Port 端口号 Reconn ...

  9. 牛客竞赛&&mjt的毒瘤赛

    题目链接 https://ac.nowcoder.com/acm/contest/368/F 思路 询问可以离线. 然后每个节点上建32个权值线段树(权值不大,其实只要20颗) 记录每一位权值为x(如 ...

  10. codevs1048石子归并

    codevs1048 石子归并  时间限制: 1 s  空间限制: 128000 KB  题目等级 : 黄金 Gold 传送门  http://codevs.cn/problem/1048/ 题目描述 ...