Java字符集編碼的自動識別 jchardet

jopen 12年前發布 | 51K 次閱讀 Java 常用工具包

jchardet是mozilla自動字符集探測算法代碼的java移植。這個算法的最初作者是frank Tang,C++源代碼在http://lxr.mozilla.org/mozilla/source/intl/chardet/,可以從http: //www.mozilla.org/projects/intl/chardet.html 得到更多關于這個算法的信息。
示例代碼:

        // Initalize the nsDetector() ;
        int lang = (argv.length == 2)? Integer.parseInt(argv[1])
                                         : nsPSMDetector.ALL ;
        nsDetector det = new nsDetector(lang) ;

    // Set an observer...
    // The Notify() will be called when a matching charset is found.

    det.Init(new nsICharsetDetectionObserver() {
            public void Notify(String charset) {
                HtmlCharsetDetector.found = true ;
                System.out.println("CHARSET = " + charset);
            }
    });

    URL url = new URL(argv[0]);
    BufferedInputStream imp = new BufferedInputStream(url.openStream());

    byte[] buf = new byte[1024] ;
    int len;
    boolean done = false ;
    boolean isAscii = true ;

    while( (len=imp.read(buf,0,buf.length)) != -1) {

            // Check if the stream is only ascii.
            if (isAscii)
                isAscii = det.isAscii(buf,len);

            // DoIt if non-ascii and not done yet.
            if (!isAscii && !done)
                done = det.DoIt(buf,len, false);
    }
    det.DataEnd();

    if (isAscii) {
       System.out.println("CHARSET = ASCII");
       found = true ;
    }</pre> 


項目主頁:http://www.baiduhome.net/lib/view/home/1324995361999

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!