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

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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值