使用ICU4J探测文档编码

网页源码的编码探测一般有两种方式,一种是通过分析网页源码中Meta信息,比如contentType,来取得编码,但是某些网页不的contentType中不含任何编码信息,这时需要通过第二种方式进行探测,第二种是使用统计学和启发式方法对网页源码进行编码探测。ICU4J就是基于第二种方式的类库。由IBM提供。

下面的例子演示了一个简单的探测过程。

package org.mingyuan.icu4j;

import java.io.IOException;
import java.io.InputStream;


import com.ibm.icu.text.CharsetDetector;
import com.ibm.icu.text.CharsetMatch;

/**
* 本类使用ICU4J包进行文档编码获取
* @author [email protected]
*
*/
public class EncodeDetector {
/**
* 获取编码
* @throws IOException
* @throws Exception
*/
public static String getEncode(byte[] data,String url){
   CharsetDetector detector = new CharsetDetector();
   detector.setText(data);
   CharsetMatch match = detector.detect();
   String encoding = match.getName();
   System.out.println("The Content in " + match.getName());
   CharsetMatch[] matches = detector.detectAll();
   System.out.println("All possibilities");
   for (CharsetMatch m : matches) {
    System.out.println("CharsetName:" + m.getName() + " Confidence:"
      + m.getConfidence());
   }
   return encoding;
}
public static String getEncode(InputStream data,String url) throws IOException{
   CharsetDetector detector = new CharsetDetector();
   detector.setText(data);
   CharsetMatch match = detector.detect();
   String encoding = match.getName();
   System.out.println("The Content in " + match.getName());
   CharsetMatch[] matches = detector.detectAll();
   System.out.println("All possibilities");
   for (CharsetMatch m : matches) {
    System.out.println("CharsetName:" + m.getName() + " Confidence:"
      + m.getConfidence());
   }
   return encoding;
}
}

你可能感兴趣的:(exception,String,IBM,url,文档,encoding)