1.通过把未知编码字符串,用猜想的编码再解码,观察字符串是不是正确还原了。
原理:假如目标编码没有数组中的字符,那么编码会破坏,无法还原。
缺点:假如字符少,而正巧错误的猜想编码中有这种字节,就会出错。
如:new String("tested str".getBytes("enc"),"enc")
2.大多数时候,我们只要判断本地平台编码和utf8,utf8编码相当有规律,所以可以分析是否是utf9,否则使用本地编码。
原理:分析byte[]来判断规律。
缺点:有时,个别本地编码字节在utf8中也会出现,导致出错,需要分析。
如转贴得函数:
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedBlockStart.gif)
public static boolean isValidUtf8(byte[] b,int aMaxCount)...{
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)
int lLen=b.length,lCharCount=0;
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)
for(int i=0;i
byte lByte=b[i++];//to fast operation, ++ now, ready for the following for(;;)
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)
if(lByte>=0) continue;//>=0 is normal ascii
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)
if(lByte<(byte)0xc0 || lByte>(byte)0xfd) return false;
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)
int lCount=lByte>(byte)0xfc?5:lByte>(byte)0xf8?4
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)
:lByte>(byte)0xf0?3:lByte>(byte)0xe0?2:1;
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)
if(i+lCount>lLen) return false;
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)
for(int j=0;j=(byte)0xc0) return false;
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)
}
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)
return true;
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)
}
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)
相应地,一个使用上述方法的例子如下:
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)
public static String getUrlParam(String aStr,String aDefaultCharset)
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedBlockStart.gif)
throws UnsupportedEncodingException...{
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)
if(aStr==null) return null;
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)
byte[] lBytes=aStr.getBytes("ISO-8859-1");
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)
return new String(lBytes,StringUtil.isValidUtf8(lBytes)?"utf8":aDefaultCharset);
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)
} 3.按编码规则,一字字比照。
优点是错物更少,缺点是太费资源。
字符检测类如下:http://dev.csdn.net/Develop/article/10/10961.shtm
阅读(999) | 评论(0) | 转发(0) |