您的位置:首页 > 编程语言 > Java开发

Java

2016-07-21 12:01 393 查看
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

import info.monitorenter.cpdetector.io.ASCIIDetector;
import info.monitorenter.cpdetector.io.CodepageDetectorProxy;
import info.monitorenter.cpdetector.io.JChardetFacade;
import info.monitorenter.cpdetector.io.ParsingDetector;
import info.monitorenter.cpdetector.io.UnicodeDetector;

/**
* cpdetector这个开源的jar包可以自动判断当前文件的内容编码,从而在读取的时候选择正确的编码读取,避免乱码问题;
* @author hukr
*
*/
public class CpdetectorTest {

public static String getCharset(String path) throws IOException{
/**
* detector是探测器,它把探测任务交给具体的探测实现类的实例完成。
* cpDetector内置了一些常用的探测实现类,这些探测实现类的实例可以通过add方法 加进来,如ParsingDetector、
* JChardetFacade、ASCIIDetector、UnicodeDetector。
* detector按照“谁最先返回非空的探测结果,就以该结果为准”的原则返回探测到的
* 字符集编码。使用需要用到三个第三方JAR包:antlr.jar、chardet.jar和cpdetector.jar
* cpDetector是基于统计学原理的,不保证完全正确。
*/
CodepageDetectorProxy detector = CodepageDetectorProxy.getInstance();

/**
* ParsingDetector可用于检查HTML、XML等文件或字符流的编码,构造方法中的参数用于
* 指示是否显示探测过程的详细信息,为false不显示。
*/
detector.add(new ParsingDetector(false));////如果不希望判断xml的encoding,而是要判断该xml文件的编码,则可以注释掉

/**
* JChardetFacade封装了由Mozilla组织提供的JChardet,它可以完成大多数文件的编码
* 测定。所以,一般有了这个探测器就可满足大多数项目的要求,如果你还不放心,
* 可以 再多加几个探测器,比如下面的ASCIIDetector、UnicodeDetector等。
*
*/

detector.add(JChardetFacade.getInstance());  // 用到antlr.jar、chardet.jar
// ASCIIDetector用于ASCII编码测定
detector.add(ASCIIDetector.getInstance());
// UnicodeDetector用于Unicode家族编码的测定
detector.add(UnicodeDetector.getInstance());
Charset charset = null;
String charsetName;
File file = new File(path);
try {
charset = detector.detectCodepage(file.toURI().toURL());
//detector不仅可以用于探测文件的编码,也可以探测任意输入的文本流的编码,方法是调用其重载形式:
//charset=detector.detectCodepage(待测的文本输入流,测量该流所需的读入字节数);
} catch (IOException e) {
e.printStackTrace();
}

if(charset != null){
charsetName = charset.name();
System.out.println(file.getName() + "编码是:" + charsetName);
}else {
charsetName = "";
System.out.println(file.getName() +"编码未知");
}
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file),charsetName));
String line = null;
String lines = "";
while ((line = reader.readLine()) != null) {
lines += line + "\n";
}
reader.close();
//return 返回结果
return lines;
// return path;
}

public static void main(String[] args) throws Exception {
//GBK.txt编码是:GB2312
System.out.println(getCharset("./GBK.txt"));
System.out.println(getCharset("./UTF.txt"));

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java