icu4j java_使用ICU4J探测文档编码 | 学步园

本文介绍如何利用ICU4J库探测不含编码信息的网页源码的编码。ICU4J采用统计学和启发式方法,通过分析内容来确定编码。示例代码展示了探测过程。
摘要由CSDN通过智能技术生成

网页源码的编码探测一般有两种方式,一种是通过分析网页源码中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、付费专栏及课程。

余额充值