字符集编码的自动识别jchardet

来源:互联网 发布:淘宝网冬季新款女装 编辑:程序博客网 时间:2024/05/14 09:41

什么是jchardet?


jchardet是mozilla自动字符集探测算法代码的java移植,其源代码可以从sourceforge下载。这个算法的最初作者是frank Tang,C++源代码在http://www.infomall.cn/cgi-bin/mallgate/20040514/http://lxr.mozilla.org/mozilla/source/intl/chardet/,可以从http://www.infomall.cn/cgi-bin/mallgate/20040514/http://www.mozilla.org/projects/intl/chardet.html得到更多关于这个算法的信息。

编译及应用


  将下载后的chardet.zip解压缩后,到~/mozilla/intl/chardet/java/目录下,运行ant即可在dist/lib目录下生成chardet.jar,将这个jar包加入CLASSPATH.然后
运行:java org.mozilla.intl.chardet.HtmlCharsetDetector http://hedong.3322.org
结果:CHARSET = GB18030
运行:java org.mozilla.intl.chardet.HtmlCharsetDetector http://www.wesnapcity.com/
结果:CHARSET = ASCII
运行:java org.mozilla.intl.chardet.HtmlCharsetDetector http://www.wesnapcity.com/blog/
结果:CHARSET = UTF-8

编程使用


  下面就jchardet.jar中的HtmlCharsetDetector.java,对调用jchardet过程予以说明:
//实现nsICharsetDetectionObserver接口,这个接口只有一个Notify()方法.当jchardet引擎自己认为已经识别出字符串的字符集后(不论识别的对错),都会调用这个Notify方法。
nsICharsetDetectionObserver cdo=new nsICharsetDetectionObserver() {
  public void Notify(String charset) {
   HtmlCharsetDetector.found = true ;
   System.out.println("CHARSET = " + charset);
  }
};
/**
* 初始化nsDetector()
*lang为一个整数,用以提示语言线索,可以提供的语言线索有以下几个:
*
  1. Japanese
  2. Chinese
  3. Simplified Chinese
  4. Traditional Chinese
  5. Korean
  6. Dont know (默认)

*/
nsDetector det = new nsDetector(lang) ;
// 设置一个Oberver
det.Init(cdo);
BufferedInputStream imp = new BufferedInputStream(url.openStream());
byte[] buf = new byte[1024] ;
boolean done = false ;  //是否已经确定某种字符集
boolean isAscii = true ;//假定当前的串是ASCII编码
while( (len=imp.read(buf,0,buf.length)) != -1) {
  // 检查是不是全是ascii字符,当有一个字符不是ASC编码时,则所有的数据即不是ASCII编码了。
  if (isAscii) isAscii = det.isAscii(buf,len);
  // 如果不是ascii字符,则调用DoIt方法.
  if (!isAscii && !done) done = det.DoIt(buf,len, false);//如果不是ASCII,又还没确定编码集,则继续检测。
}
det.DataEnd();//最后要调用此方法,此时,Notify被调用。
if (isAscii) {
System.out.println("CHARSET = ASCII");
found = true ;
}
if (!found) {//如果没找到,则找到最可能的那些字符集
String prob[] = det.getProbableCharsets() ;
for(int i=0; i   System.out.println("Probable Charset = " + prob[i]);
}
}