🪡 Java Unicode 转中文
在 Java 中,将 Unicode 转换成中文可以通过以下几种方式实现:
1. 使用 String 的 \u 转义符
如果你已经有一个 Unicode 字符串(例如 "\\u4F60\\u597D"),你可以直接在 Java 字符串中使用 Unicode 转义符,并让 Java 自动解析成相应的中文字符。
javaCopy
public class UnicodeToChinese {
public static void main(String[] args) {
// 直接用 Unicode 转义字符
String unicodeStr = "\u4F60\u597D"; // "你好"
System.out.println(unicodeStr);
}
}
输出:
plain textCopy
你好
2. 将 Unicode 字符串转换为中文
如果你从外部获取了一个 Unicode 字符串(如:\u4F60\u597D),并希望将其转换为对应的中文字符,可以通过 String 类的 replace() 方法手动替换 Unicode 字符串中的 \u 转义符,或者使用正则表达式进行处理。一个常见的方法是使用 Pattern 和 Matcher 来匹配和替换 Unicode 转义。
例如,假设你有一个 Unicode 字符串,形式类似于 \u4F60\u597D,你可以通过以下方式进行转换:
javaCopy
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class UnicodeToChinese {
public static void main(String[] args) {
String unicodeStr = "\\u4F60\\u597D"; // "你好" 的 Unicode 表示
// 正则表达式匹配 \u 开头的 Unicode 字符
Pattern pattern = Pattern.compile("\\\\u([0-9a-fA-F]{4})");
Matcher matcher = pattern.matcher(unicodeStr);
StringBuffer result = new StringBuffer();
while (matcher.find()) {
// 获取每个 Unicode 字符,并转换为相应的字符
String unicode = matcher.group(1);
char unicodeChar = (char) Integer.parseInt(unicode, 16);
matcher.appendReplacement(result, String.valueOf(unicodeChar));
}
matcher.appendTail(result);
// 输出转换后的中文
System.out.println(result.toString()); // 输出 "你好"
}
}
3. 使用 URLDecoder 解码 Unicode 字符串(如果 Unicode 是 URL 编码)
有时你可能会遇到 URL 编码的 Unicode 字符串(如 %u4F60%u597D)。此时,你可以使用 URLDecoder 来解码并转换成中文。
javaCopy
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
public class UnicodeToChinese {
public static void main(String[] args) throws UnsupportedEncodingException {
String unicodeStr = "%u4F60%u597D"; // 可能是 URL 编码后的 Unicode 字符串
// 使用 URLDecoder 解码
String decodedStr = URLDecoder.decode(unicodeStr, "UTF-8");
System.out.println(decodedStr); // 输出 "你好"
}
}
总结
根据你的实际需求,选择合适的方法即可。
