把自己做的工具类留个档,同时分享给大家
import java.io.UnsupportedEncodingException;
/**
* 国标汉字检查工具类
* @author 林良益
*
*/
public class GBHZUtil {
//可忽略的分隔符号
private static final String skipChar = "[\\s\\t\\r\\n]";
private static final String NOGB2312CHAR = "不是GB2312字符";
private static final String GB2312CHAR_NOHZ = "GB2312非汉字字符";
private static final String GB2312CHAR_HZ = "GB2312汉字字符";
/**
* 检查字符窜是否是国标字库一二级标准字库汉字
* 如果含有国标一二级字库外的汉字则返回false
* @param orgString
* @return
* @throws UnsupportedEncodingException
* 抛出改异常说明当前的java虚拟机运行环境不支持GB2312编码
*/
public static boolean validateGB2312HZ(String orgString) throws UnsupportedEncodingException{
//忽略字符中的不可见分隔符
String noSkipCharStr = orgString.replaceAll(skipChar, "");
if("".equals(noSkipCharStr)){
return false;
}
char[] charArray = noSkipCharStr.toCharArray();
String identifyResult = null;
for(char c : charArray){
identifyResult = identifyGB2312Char(c);
if(!GB2312CHAR_HZ.equals(identifyResult)){
return false;
}
}
return true;
}
/**
* 识别GB2312字符
* @param theChar
* @return
* @throws UnsupportedEncodingException
* 抛出改异常说明当前的java虚拟机运行环境不支持GB2312编码
*/
public static String identifyGB2312Char(char theChar)throws UnsupportedEncodingException{
//将字符窜转成GB2312编码
byte[] byteArray = String.valueOf(theChar).getBytes("GB2312");
//根据国标区位码编码规则,判断字符
int highBit = 0;
for(int i = 0 ; i < byteArray.length ; i++){
int offset = (byteArray[i] & 0xFF) - 0xA0;
//GB2312字符区码在1-94
if(offset >= 1 && offset <= 94){
if(highBit == 0){
//找到一个汉字区码
highBit = offset;
}else{
//找到一个GB2312位码
if(highBit < 16 || highBit > 87){
return GB2312CHAR_NOHZ;
}else{
//位码在1-94区间 (其中对于第55 区的位码,最大为89
if(highBit == 55 && offset > 89){
return GB2312CHAR_NOHZ;
}else{
return GB2312CHAR_HZ;
}
}
}
}else{
//不是一个GB2312字符
return NOGB2312CHAR;
}
}
return NOGB2312CHAR;
}
}