借助JCharDet获取文件字符集
前段时间,在学习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获取文件字符集的更多相关文章
- Java如何获取文件编码格式
1:简单判断是UTF-8或不是UTF-8,因为一般除了UTF-8之外就是GBK,所以就设置默认为GBK. 按照给定的字符集存储文件时,在文件的最开头的三个字节中就有可能存储着编码信息,所以,基本的原 ...
- JAVA中获取文件MD5值的四种方法
JAVA中获取文件MD5值的四种方法其实都很类似,因为核心都是通过JAVA自带的MessageDigest类来实现.获取文件MD5值主要分为三个步骤,第一步获取文件的byte信息,第二步通过Messa ...
- java读取resource/通过文件名获取文件类型
java读取resource java读取resource目录下文件的方法: 借助Guava库的Resource类 Resources.getResource("test.txt" ...
- Atitit.检测文本文件的编码 自动获取文件的中文编码
Atitit.检测文本文件的编码 自动获取文件的中文编码 1 不能使用load来检测编码..1 2 使用convert来检测编码1 3 程序检测文本编码2 3.1 根据utf bom头2 3.2 检测 ...
- C++获取文件夹中所有文件
获取文件夹中的文件,用到过很多次,每次用的时候都要去查下,很烦,所以想自己写下,当然,借鉴了很多其他大佬的博客 主要实现的函数,如下: void getFiles( string path, vect ...
- 获取文件的缩略图Thumbnail和通过 AQS - Advanced Query Syntax 搜索本地文件
演示如何获取文件的缩略图 FileSystem/ThumbnailAccess.xaml <Page x:Class="XamlDemo.FileSystem.ThumbnailAcc ...
- FastDFS 通过文件名获取文件信息
/** * 获取文件信息 * * param string group_name 文件所在的组名 * param string file_id 文件id(如: M00/09/BE/rBBZolgj6O ...
- c# .net获取文件夹下的所有文件(多层递归),并获取区间数据(Jsion,xml等数据)写出到处理文件,学习分享~
static void Main(string[] args) { string path = string.Format(@"C:\Users\Administrator\D ...
- java 获取文件列表,并按照文件名称排序
需求:获取全部的日志文件,并按照文件名称倒序排列,把最新的文件放在最前1.获取全部的日志文件:(方法:public List<String> ergodic(File file,List& ...
随机推荐
- 有登陆认证的情况下如何使用Wisdom RESTClient?
访问REST API时,很多系统需要登陆认证,登陆成功以后才允许访问API.下面介绍一下有登陆认证情况下如何使用 Wisdom RESTClient测试API的方法. 方法很简单即在浏览器上成功登录系 ...
- 数据分析之pandas02
DataFrame 一.DataFrame DataFrame是一个[表格型]的数据结构.DataFrame又按一定顺序排列的多列数据组成,设计初衷是将Series的使用场景从一维扩展到多维.Date ...
- Spring Boot 2 (七):Spring Boot 如何解决项目启动时初始化资源
Spring Boot 2 (七):Spring Boot 如何解决项目启动时初始化资源 在项目启动的时候需要做一些初始化的操作,比如初始化线程池,提前加载好加密证书等.今天就给大家介绍一个 Spri ...
- [c/c++] programming之路(8)、汇编、求模、自增自减
一.插入汇编 #include<stdio.h> void main(){ ; num=num+; //插入汇编语言 _asm{ mov eax,num;//eax是一个存储器,将num的 ...
- Codeforces 832E Vasya and Shifts - 高斯消元
题目传送门 快速的传送门I 快速的传送门II 题目大意 (题意比较复杂,请自行阅读原题) 可以将原题的字母都看成它们的在字符表中的下标,这样问题就变成给定$n$个$m$维向量$\vec{a_{1}}, ...
- shelve模块,sys模块,logging模块
1.shelve模块 用于序列化的模块,shelve模块比pickle模块简单,只有open函数,返回类似字典的对象,可读可写;key必须为字符串,而值可以是python所支持的数据类型. impor ...
- uniGUI试用笔记(五)
uniGUI的主窗体可以采用多页面方式进行管理,参考网上的资料,都是用TUniFrame + TUniPageControl 来实现,尝试了一下,效果还不错,如下图: 用TUniFrame 能够使用继 ...
- 给ThinkPad E470C 换个高分屏(1080P)
- C# 禁止任务管理器关闭
http://www.cnblogs.com/luomingui/archive/2011/06/25/2090130.html 测试了好像没用的.不知道什么原因
- P4980 【模板】Polya定理
思路 polya定理的模板题,但是还要加一些优化 题目的答案就是 \[ \frac{\sum_{i=1}^n n^{gcd(i,n)}}{n} \] 考虑上方的式子怎么求 因为\(gcd(i,n)\) ...