Public classFontutil { Public Static voidMain (string[] args) {System.out.println (Chinatounicode ("Not logged in!" ")); System.out.println (Decodeunicode ("\u672a\u767b\u9646\uff01")); } /*** Translate Chinese into Unicode code * *@paramSTR *@return */ Public Staticstring Chinatounicode (String str) {string result= ""; for(inti = 0; I < str.length (); i++) { intCHR1 = (Char) Str.charat (i); if(Chr1 >= 19968 && chr1 <= 171941) {//Chinese Character Range \u4e00-\u9fa5 (Chinese)Result + = "\\u" +integer.tohexstring (CHR1); } Else{result+=Str.charat (i); } } returnresult; } /*** Determine if it is a Chinese character * *@paramc *@return */ Public Static BooleanIschinese (Charc) {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 to Chinese Public StaticString Decodeunicode (FinalString Unicode) {StringBuffer string=NewStringBuffer (); String[] Hex= Unicode.split ("\\\\u"); for(inti = 0; i < hex.length; i++) { Try { //Chinese Character Range \u4e00-\u9fa5 (Chinese) if(Hex[i].length () >=4) {//take the first four to determine if it is a Chinese characterString Chinese = hex[i].substring (0, 4); Try { intCHR = Integer.parseint (Chinese, 16); BooleanIschinese = Ischinese ((Char) CHR); //success of conversion, judging whether within the range of Chinese characters if(Ischinese) {//within the range of Chinese characters//Append As StringString.append ((Char) CHR); //and append the following charactersString 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]); } } returnstring.tostring (); } }
Java Chinese and Unicode mutual transfer