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

来源:互联网 发布:北京数据分析培训机构 编辑:程序博客网 时间:2024/05/18 11:48

 

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
原创粉丝点击