? ? ? ? 今天在開發(fā)項目的時候,第三方提供的接口返回的數(shù)據(jù)是經(jīng)過Unicode編碼的,我們使用的時候多有不便,所以經(jīng)過代碼將Unicode解碼才能使用,故記錄一下使用Java進行Unicode和中文的互轉(zhuǎn)。通常我們在安全優(yōu)先級不是特別高但是又不想使用明文的情況下就可以使用這中方式進行加密、解密。
加密:將中文字符轉(zhuǎn)換成Unicode字符
/**
* @Title: unicodeEncode
* @Description: 將中文字符轉(zhuǎn)換成Unicode字符
* @param string
* @return
*/
public static String unicodeEncode(String string) {
char[] utfBytes = string.toCharArray();
String unicodeBytes = "";
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;
}
return unicodeBytes;
}
?解碼:將Unicode的編碼轉(zhuǎn)換為中文da文章來源:http://www.zghlxwxcb.cn/news/detail-641820.html
/**
* @param string
* @return 轉(zhuǎn)換之后的內(nèi)容
* @Title: unicodeDecode
* @Description: 將Unicode的編碼轉(zhuǎn)換為中文
*/
public static String unicodeDecode(String string) {
Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");
Matcher matcher = pattern.matcher(string);
char ch;
while (matcher.find()) {
ch = (char) Integer.parseInt(matcher.group(2), 16);
string = string.replace(matcher.group(1), ch + "");
}
return string;
}
單元測試:可以看到只有中文會加密、解碼。英文是不影響的。文章來源地址http://www.zghlxwxcb.cn/news/detail-641820.html
public static void main(String[] args) {
String str = "你好,hello word";
// 加密 中文 -> Unicode
String unicodeEncode = unicodeEncode(str);
System.out.println(str + " ---> " + unicodeEncode);
// 解碼 Unicode -> 中文
String zh_str = unicodeDecode(unicodeEncode);
System.out.println(unicodeEncode + " ---> " + zh_str);
}
到了這里,關(guān)于Java Unicode和中文編碼轉(zhuǎn)換的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!