Chinaunix首页 | 论坛 | 博客
  • 博客访问: 29960439
  • 博文数量: 708
  • 博客积分: 12163
  • 博客等级: 上将
  • 技术积分: 8240
  • 用 户 组: 普通用户
  • 注册时间: 2007-12-04 20:59
文章分类

全部博文(708)

分类: Java

2008-07-14 10:00:33

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
阅读(999) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~