使用ICU4J探测文档编码

曾经使用过这个东东,还是不错的,中国人的一篇论文,最早的时候好像是在哪个开源浏览器里。

引用一片博客,做个注记.转自http://hi.baidu.com/cnjsp/blog/item/da18d0581e59f68a810a18e8.html

 

网页源码的编码探测一般有两种方式,一种是通过分析网页源码中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 mingyuanonline@gmail.com
*
*/
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;
}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值