1 import java.io.UnsupportedEncodingException;
 2 
 3 public class TestUnicode{
 4 
 5     public static void main(String[] args) throws UnsupportedEncodingException {
 6         String s = "简介";
 7         System.out.println(s+" --的unicode编码是:"+gbEncoding(s));
 8         System.out.println(gbEncoding(s) + " --转换成中文是:"+decodeUnicode(gbEncoding(s)));
 9         
10         //System.out.println(gbEncoding(s) + " --转换成中文是:"+decodeUnicode("\\u7b80\\u4ecb"));
11     }
12     
13     /*
14      * 中文转unicode编码
15      */
16     public static String gbEncoding(final String gbString) {
17         char[] utfBytes = gbString.toCharArray();
18         String unicodeBytes = "";
19         for (int i = 0; i < utfBytes.length; i++) {
20             String hexB = Integer.toHexString(utfBytes[i]);
21             if (hexB.length() <= 2) {
22                 hexB = "00" + hexB;
23             }
24             unicodeBytes = unicodeBytes + "\\u" + hexB;
25         }
26         return unicodeBytes;
27     }
28     /*
29      * unicode编码转中文
30      */
31     public static String decodeUnicode(final String dataStr) {
32         int start = 0;
33         int end = 0;
34         final StringBuffer buffer = new StringBuffer();
35         while (start > -1) {
36             end = dataStr.indexOf("\\u", start + 2);
37             String charStr = "";
38             if (end == -1) {
39                 charStr = dataStr.substring(start + 2, dataStr.length());
40             } else {
41                 charStr = dataStr.substring(start + 2, end);
42             }
43             char letter = (char) Integer.parseInt(charStr, 16); // 16进制parse整形字符串。
44             buffer.append(new Character(letter).toString());
45             start = end;
46         }
47         return buffer.toString();
48     }
49 }

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-02
  • 2022-12-23
  • 2021-12-07
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-07-06
  • 2022-12-23
  • 2022-12-23
  • 2022-01-25
  • 2022-12-23
相关资源
相似解决方案