/**
* Unicode工具类
*/
public class UnicodeUtils {
//使用volatile关键字保其可见性
volatile private static UnicodeUtils instance = null;
private UnicodeUtils() {
}
public static UnicodeUtils getInstance() {
try {
if (instance != null) {//懒汉式
} else {
//创建实例之前可能会有一些准备性的耗时工作
Thread.sleep(300);
synchronized (UnicodeUtils.class) {
if (instance == null) {//二次检查
instance = new UnicodeUtils();
}
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
return instance;
}
/**
* 中文转unicode编码
*/
public String SetEncoding(String gbString) {
String unicodeBytes = "";
if (gbString != null) {
try {
char[] utfBytes = gbString.toCharArray();
for (int i = 0; i < utfBytes.length; i++) {
String hexB = Integer.toHexString(utfBytes[i]);
if (hexB.length() <= 2) {
hexB = "00" + hexB;
}
unicodeBytes = unicodeBytes + "u" + hexB;
}
} catch (Exception e) {
unicodeBytes = gbString;
}
}
return unicodeBytes;
}
/**
* unicode编码转中文
*/
public String GetUnicode(String dataStr) {
String unicodeBytes = "";
if (dataStr != null) {
try {
int start = 0;
int end = 0;
final StringBuffer buffer = new StringBuffer();
while (start > -1) {
end = dataStr.indexOf("u", start + 1);
String charStr = "";
if (end == -1) {
charStr = dataStr.substring(start + 1, dataStr.length());
} else {
charStr = dataStr.substring(start + 1, end);
}
char letter = (char) Integer.parseInt(charStr, 16); // 16进制parse整形字符串。
buffer.append(new Character(letter).toString());
start = end;
}
unicodeBytes = buffer.toString();
} catch (Exception e) {
unicodeBytes = dataStr;
}
}
return unicodeBytes;
}
}
UnicodeUtils
最新推荐文章于 2023-05-08 07:49:24 发布