几种判断字符集编码的方法(Java) .未完

 

1.通过把未知编码字符串,用猜想的编码再解码,观察字符串是不是正确还原了。
原理:假如目标编码没有数组中的字符,那么编码会破坏,无法还原。
缺点:假如字符少,而正巧错误的猜想编码中有这种字节,就会出错。

如:new String("tested str".getBytes("enc"),"enc")

2.大多数时候,我们只要判断本地平台编码和utf8,utf8编码相当有规律,所以可以分析是否是utf9,否则使用本地编码。
原理:分析byte[]来判断规律。
缺点:有时,个别本地编码字节在utf8中也会出现,导致出错,需要分析。

如转贴得函数:

public   static   boolean  isValidUtf8( byte [] b, int  aMaxCount) {

int lLen=b.length,lCharCount=0;

for(int i=0;i 
byte lByte=b[i++];//to fast operation, ++ now, ready for the following for(;;)

if(lByte>=0continue;//>=0 is normal ascii

if(lByte<(byte)0xc0 || lByte>(byte)0xfdreturn false;

int lCount=lByte>(byte)0xfc?5:lByte>(byte)0xf8?4

:lByte
>(byte)0xf0?3:lByte>(byte)0xe0?2:1;

if(i+lCount>lLen) return false;

for(int j=0;j=(byte)0xc0return false;

}


return   true ;

}

相应地,一个使用上述方法的例子如下:

public   static  String getUrlParam(String aStr,String aDefaultCharset)

throws  UnsupportedEncodingException {

if(aStr==nullreturn null;

byte[] lBytes=aStr.getBytes("ISO-8859-1");

return new String(lBytes,StringUtil.isValidUtf8(lBytes)?"utf8":aDefaultCharset);

}

3.按编码规则,一字字比照。
优点是错物更少,缺点是太费资源。

字符检测类如下:http://dev.csdn.net/Develop/article/10/10961.shtm
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值