1 public static void main(String[] args) { 2 String s = "测试"; 3 String tt = gbEncoding(s); // String tt1 = "你好,我想给你说一个事情"; 4 System.err.println(s + " to unicode :" + tt); 5 System.err.println(tt + " decode unicode :" + decodeUnicode(tt)); 6 } 7 8 public static String gbEncoding(final String gbString) { 9 char[] utfBytes = gbString.toCharArray(); 10 String unicodeBytes = ""; 11 for (int byteIndex = 0; byteIndex < utfBytes.length; byteIndex++) { 12 String hexB = Integer.toHexString(utfBytes[byteIndex]); 13 if (hexB.length() <= 2) { 14 hexB = "00" + hexB; 15 } 16 unicodeBytes = unicodeBytes + "\u" + hexB; 17 } 18 return unicodeBytes; 19 } 20 21 public static String decodeUnicode(final String dataStr) { 22 int start = 0; 23 int end = 0; 24 final StringBuffer buffer = new StringBuffer(); 25 while (start > -1) { 26 end = dataStr.indexOf("\u", start + 2); 27 String charStr = ""; 28 if (end == -1) { 29 charStr = dataStr.substring(start + 2, dataStr.length()); 30 } else { 31 charStr = dataStr.substring(start + 2, end); 32 } 33 char letter = (char) Integer.parseInt(charStr, 16); // 16进制parse整形字符串。 34 buffer.append(new Character(letter).toString()); 35 start = end; 36 } 37 return buffer.toString(); 38 }