几种判断字符集编码的方法(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>=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);
}
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>=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);
}
3.按编码规则,一字字比照。
优点是错物更少,缺点是太费资源。
字符检测类如下:http://dev.csdn.net/Develop/article/10/10961.shtm
- 几种判断字符集编码的方法(Java) .未完
- Java 判断文件的字符集编码
- 判断文本文件的字符集编码
- 收藏 java 如何判断txt的编码字符集
- Java写入文件的几种方法(指定编码)
- java中的字符集的编码
- Java判断字符串是否为数字的几种方法
- java判断回文字符串的几种方法
- java判断是否为数字的几种方法
- Java判断字符串是否为空的几种方法
- Java判断数字为几位数的两种方法
- 利用java判断文件的编码方法
- eclipse PyDev 字符集编码设置的3种方法
- 二进制的几种编码表示方法
- [Java] java 的字符集和编码方案
- 常见的几种字符集
- 常见的几种字符集
- Windows Notepad 判断字符集的方法
- 日本関係サイト
- dwr2.0 中 util.js脚本提供的实用方法调用说明
- Eclipse下配置C和C++的开发环境(过程篇)
- 类型信息
- tab切换
- 几种判断字符集编码的方法(Java) .未完
- XML解析之xsi:nil="true"(续)
- 影响中国发展的七大垂直搜索引擎!!
- 探索 Eclipse 的 Ajax Toolkit Framework
- VSS使用手册
- Linux平台下的JNI开发[88250原创]
- (修改后)将数组进行合并
- 深入 Lucene 索引机制
- 彩云之巅(二) 启程