com.datastax.util.lang.EncodingUtil Maven / Gradle / Ivy
The newest version!
package com.datastax.util.lang;
/**
* User: Anders Hong
* Date: 9/18/13
* Time: 12:31 PM
*/
public class EncodingUtil {
/**
* 中文转-->unicode
*
* @param str
* @return 反回unicode编码
*/
public static String chinaToUnicode(String str) {
StringBuffer result = new StringBuffer();
for (int i = 0; i < str.length(); i++) {
int chr1 = (char) str.charAt(i);
result.append("\\u" + Integer.toHexString(chr1));
}
return result.toString();
}
/**
* 把unicode转化为中文
*
* @param str
* @return
*/
public static String unicodeToChinese(String str) {
if (containsChinese(str))//判断是否有中文字符
return str;
if (str.indexOf("\\u") == -1 || str == null || "".equals(str.trim())) {/*若不是unicode,则直接返回*/
return str.replaceAll("\\\\ ", " ");//删掉英文中的\,such as "default\ value1"
/* 主要是针对 zk 中的国际化问题 */
}
StringBuffer sb = new StringBuffer();
if (!str.startsWith("\\u")) {/*若开头不是unicode,如“abc\u4e2d\u56fd” */
int index = str.indexOf("\\u");
sb.append(str.substring(0, index));
str = str.substring(index);
}
if (str.endsWith(":")) /*如“\u4e2d\u56fd:” */ {
str = str.substring(0, str.length() - 1);
}
String[] chs = str.trim().split("\\\\u");
for (int i = 0; i < chs.length; i++) {
String ch = chs[i].trim();
if (ch != null && !"".equals(ch)) {
sb.append((char) Integer.parseInt(ch.substring(0, 4), 16));
if (ch.length() > 4) {
sb.append(ch.substring(4));
}
}
}
return sb.toString();
}
public static boolean isAllChinese(String text) {
char[] charArray = text.toCharArray();
for (int i = 0; i < charArray.length; i++) {
if ((charArray[i] >= 0x4e00) && (charArray[i] <= 0x9fbb)) {
//return true;
}else {
return false;
}
}
return true;
}
public static boolean containsChinese(String word) {
char[] input = word.trim().toCharArray();
for (int i = 0; i < input.length; i++) {
if (Character.toString(input[i]).matches("[\u4E00-\u9FA5]+")) {
return true;
}
}
return false;
}
public static String resolveUnicode(String oldValue, boolean isToUnicode) {
if (isToUnicode) {
return chinaToUnicode(oldValue);
} else {
return unicodeToChinese(new String(oldValue));
}
}
}