net.unmz.java.util.unicode.UnicodeUtils Maven / Gradle / Ivy
package net.unmz.java.util.unicode;
/**
* Project Name: 常用工具类集合
* 功能描述:Unicode转换工具类
*
* @author [email protected]
* @version 1.0
* @date 2018-1-22 12:12
* @since JDK 1.8
*/
public class UnicodeUtils {
/**
* 字符转Unicode
* @param gbString
* @return
*/
public static String encodeUnicode(final String gbString) {
char[] utfBytes = gbString.toCharArray();
String unicodeBytes = "";
for (int byteIndex = 0; byteIndex < utfBytes.length; byteIndex++) {
String hexB = Integer.toHexString(utfBytes[byteIndex]); //转换为16进制整型字符串
if (hexB.length() <= 2) {
hexB = "00" + hexB;
}
unicodeBytes = unicodeBytes + "\\u" + hexB;
}
System.out.println("unicodeBytes is: " + unicodeBytes);
return unicodeBytes;
}
/**
* Unicode转字符
* @param dataStr
* @return
*/
public static String decodeUnicode(final String dataStr) {
int start = 0;
int end = 0;
final StringBuffer buffer = new StringBuffer();
while (start > -1) {
end = dataStr.indexOf("\\u", start + 2);
String charStr = "";
if (end == -1) {
charStr = dataStr.substring(start + 2, dataStr.length());
} else {
charStr = dataStr.substring(start + 2, end);
}
char letter = (char) Integer.parseInt(charStr, 16); // 16进制parse整形字符串。
buffer.append(new Character(letter).toString());
start = end;
}
return buffer.toString();
}
}