读书人

JAVA中检拆字符编码

发布时间: 2012-08-28 12:37:01 作者: rapoo

JAVA中检测字符编码

一、按不同编码方式进行试转换,比较转换后与转换前是否相同:

// 识别字符串编码

public static String getEncoding(String str) {

? if (str == null || str.trim().length() < 1)

? ? return "";

? // 常用字符编码数组

? String[] encodes = new String[] { "GBK", "ISO-8859-1", "GB2312",

? ? ? "GB18030", "UTF-8" };

? for (String encode : encodes) {

? ? try {

? ? ? // 匹配字符编码

? ? ? if (str.equals(new String(str.getBytes(), encode))) {

? ? ? ? // 返回编码名称

? ? ? ? return encode;

? ? ? } else {

? ? ? ? continue;

? ? ? }

? ? } catch (Exception er) {

? ? }

? }

? return "";

}

?

?

二、分析byte[]来判断规律。

缺点:有时,个别本地编码字节在utf8中也会出现,导致出错,需要分析。

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

int lLen=b.length,lCharCount=0;

for(int i=0;i < lLen; i++){

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

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

if(lByte<(byte)0xc0 || lByte>(byte)0xfd) return 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)0xc0) return false;

}

return true;

}

?

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

public static String getUrlParam(String aStr,String aDefaultCharset) throws UnsupportedEncodingException{

if(aStr==null) return null;

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

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

}

?

三:使用jchardet组件:

jchardet是mozilla自动字符集探测算法代码的java移植,其源代码可以从sourceforge下载。这个算法的最初作者是frank Tang,C++源代码在

http://www.infomall.cn/cgi-bin/mallgate/20040514/

http://lxr.mozilla.org/mozilla/source/intl/chardet/,可以从

http://www.infomall.cn/cgi-bin/mallgate/20040514/

http://www.mozilla.org/projects/intl/chardet.html

得到更多关于这个算法的信息。


读书人网 >编程

热点推荐