<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.11</version>
</dependency>
import org.apache.commons.lang3.StringUtils;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
public class Test01 {
// 获取unicode码的几种方式
public static void main(String[] args) throws UnsupportedEncodingException {
// 第一种
System.err.println("第一种-----commons-lang3 toCodePoints");
String test = "a汉";
int[] codePoints = StringUtils.toCodePoints(test);
for (int codePoint : codePoints) {
System.err.println("int整型:" + codePoint);
String x = Integer.toHexString(codePoint); //16进制
if (x.length() <= 2) {
x = "\\u00" + x;
} else {
x = "\\u" + x;
}
System.err.println("unicode码" + x);
}
//第二种
System.err.println("\r\n第二种-----getBytes");
byte[] bytes = test.getBytes("unicode");
List<Object> list = new ArrayList<>();
for (byte aByte : bytes) {
// System.err.println("byte字节:" + aByte);
String x = Integer.toHexString(aByte);
if ((-2 != aByte) && (-1 != aByte)) {
list.add(x);
}
}
for (int i = 0; i < list.size(); i = i + 2) {
StringBuilder sb = new StringBuilder();
sb.append(list.get(i));
sb.append(list.get(i + 1));
if (sb.length() < 4) {
for (int j = 0; j < 4 - sb.length(); j++) {
sb.insert(0, "0");
}
}
System.err.println("unicode码" + "\\u".concat(sb.toString()));
}
// 第三种
System.err.println("\r\n第三种-----toCharArray");
char[] chars = test.toCharArray();
for (char aChar : chars) {
System.err.println("char字符:" + aChar);
String x = Integer.toHexString(aChar);
if (x.length() <= 2) {
x = "\\u00" + x;
} else {
x = "\\u" + x;
}
System.err.println("unicode码" + x);
}
}
}
第一种——-commons-lang3 toCodePoints int整型:97
unicode码\u0061
int整型:27721
unicode码\u6c49
第二种——-getBytes
unicode码\u0061
unicode码\u6c49
第三种——-toCharArray
char字符:a
unicode码\u0061
char字符:汉
unicode码\u6c49
码位转成字符
@Test
public void test_7() {
int x = 27721;
String y = new String(Character.toChars(x));
System.out.println(y); //汉
}