中国語をUnicodeコードに変換
.propertiesファイルに中国語を配置し、文字化けを防ぐためにUnicode符号化を使用する必要がある.
/**
* @author :maph
* @version :
* @date :Created in 2020-04-28 11:06
* @description: Unicode
* @modified By:
*/
public class FontUtil {
public static void main(String[] args) {
System.out.println(chinaToUnicode(" !"));
System.out.println(decodeUnicode("\u672a\u767b\u9646\uff01"));
System.out.println(chinaToUnicode(" "));
}
/**
* Unicode
*
* @param str
* @return
*/
public static String chinaToUnicode(String str) {
String result = "";
for (int i = 0; i < str.length(); i++) {
int chr1 = (char) str.charAt(i);
if (chr1 >= 19968 && chr1 <= 171941) {
// \u4e00-\u9fa5 ( )
result += "\\u" + Integer.toHexString(chr1);
} else {
result += str.charAt(i);
}
}
return result;
}
/**
*
*
* @param c
* @return
*/
public static boolean isChinese(char c) {
Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
|| ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
|| ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
|| ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
|| ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
|| ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
return true;
}
return false;
}
//Unicode
public static String decodeUnicode(final String unicode) {
StringBuffer string = new StringBuffer();
String[] hex = unicode.split("\\\\u");
for (int i = 0; i < hex.length; i++) {
try {
// \u4e00-\u9fa5 ( )
if(hex[i].length()>=4){
// ,
String chinese = hex[i].substring(0, 4);
try {
int chr = Integer.parseInt(chinese, 16);
boolean isChinese = isChinese((char) chr);
// ,
if (isChinese){
//
// string
string.append((char) chr);
//
String behindString = hex[i].substring(4);
string.append(behindString);
}else {
string.append(hex[i]);
}
} catch (NumberFormatException e1) {
string.append(hex[i]);
}
}else{
string.append(hex[i]);
}
} catch (NumberFormatException e) {
string.append(hex[i]);
}
}
return string.toString();
}
}