什麼是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.然後
結果: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 cdo=new nsICharsetDetectionObserver() {
public void Notify(String charset) {
HtmlCharsetDetector.found = true ;
System.out.println("CHARSET = " + charset);
}
};
/**
* 初始化nsDetector()
*lang爲一個整數,用以提示語言線索,可以提供的語言線索有以下幾個:
*
- Japanese
- Chinese
- Simplified Chinese
- Traditional Chinese
- Korean
- 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]);
}
}