1. <dependency>
    2. <groupId>org.apache.commons</groupId>
    3. <artifactId>commons-lang3</artifactId>
    4. <version>3.11</version>
    5. </dependency>
    1. import org.apache.commons.lang3.StringUtils;
    2. import java.io.UnsupportedEncodingException;
    3. import java.util.ArrayList;
    4. import java.util.List;
    5. public class Test01 {
    6. // 获取unicode码的几种方式
    7. public static void main(String[] args) throws UnsupportedEncodingException {
    8. // 第一种
    9. System.err.println("第一种-----commons-lang3 toCodePoints");
    10. String test = "a汉";
    11. int[] codePoints = StringUtils.toCodePoints(test);
    12. for (int codePoint : codePoints) {
    13. System.err.println("int整型:" + codePoint);
    14. String x = Integer.toHexString(codePoint); //16进制
    15. if (x.length() <= 2) {
    16. x = "\\u00" + x;
    17. } else {
    18. x = "\\u" + x;
    19. }
    20. System.err.println("unicode码" + x);
    21. }
    22. //第二种
    23. System.err.println("\r\n第二种-----getBytes");
    24. byte[] bytes = test.getBytes("unicode");
    25. List<Object> list = new ArrayList<>();
    26. for (byte aByte : bytes) {
    27. // System.err.println("byte字节:" + aByte);
    28. String x = Integer.toHexString(aByte);
    29. if ((-2 != aByte) && (-1 != aByte)) {
    30. list.add(x);
    31. }
    32. }
    33. for (int i = 0; i < list.size(); i = i + 2) {
    34. StringBuilder sb = new StringBuilder();
    35. sb.append(list.get(i));
    36. sb.append(list.get(i + 1));
    37. if (sb.length() < 4) {
    38. for (int j = 0; j < 4 - sb.length(); j++) {
    39. sb.insert(0, "0");
    40. }
    41. }
    42. System.err.println("unicode码" + "\\u".concat(sb.toString()));
    43. }
    44. // 第三种
    45. System.err.println("\r\n第三种-----toCharArray");
    46. char[] chars = test.toCharArray();
    47. for (char aChar : chars) {
    48. System.err.println("char字符:" + aChar);
    49. String x = Integer.toHexString(aChar);
    50. if (x.length() <= 2) {
    51. x = "\\u00" + x;
    52. } else {
    53. x = "\\u" + x;
    54. }
    55. System.err.println("unicode码" + x);
    56. }
    57. }
    58. }

    第一种——-commons-lang3 toCodePoints int整型:97

    unicode码\u0061

    int整型:27721

    unicode码\u6c49

    第二种——-getBytes

    unicode码\u0061

    unicode码\u6c49

    第三种——-toCharArray

    char字符:a

    unicode码\u0061

    char字符:汉

    unicode码\u6c49


    码位转成字符

    1. @Test
    2. public void test_7() {
    3. int x = 27721;
    4. String y = new String(Character.toChars(x));
    5. System.out.println(y); //汉
    6. }