从文件中读取十六进制Unicode字符串并将其转换为Java字符串?

时间:2016-09-08 19:21:53

标签: java utf-8 utf

我正在为JSON文档编写一个小解析器。 UTF字符可以表示为\u0628

如何将字符串\u0628转换为真正的Java字符?

2 个答案:

答案 0 :(得分:1)

您可以使用这样的代码:

String str = myString.split(" ")[0];
str = str.replace("\\","");
String[] arr = str.split("u");
String text = "";
for(int i = 1; i < arr.length; i++){
    int hexVal = Integer.parseInt(arr[i], 16);
    text += (char)hexVal;
}

或者您可以使用Apache Commons Lang:

import org.apache.commons.lang.StringEscapeUtils;

@Test
public void testUnescapeJava() {
    String sJava="\\u0048\\u0065\\u006C\\u006C\\u006F";
    System.out.println("StringEscapeUtils.unescapeJava(sJava):\n" + StringEscapeUtils.unescapeJava(sJava));
}


 output:
 StringEscapeUtils.unescapeJava(sJava):
 Hello

答案 1 :(得分:1)

您可以使用UTF_16字符集解析字节:

E.g。

byte[] data = {0x06, 0x28};
String string = new String(data, StandardCharsets.UTF_16);

您可以使用正则表达式

找到转义符
private static Pattern ESCAPE_PATTERN = Pattern.compile("\\\\u([0-9a-fA-F]{2})([0-9a-fA-F]{2})");

public static String replaceCharEscapes(String input) {
    Matcher m = ESCAPE_PATTERN.matcher(input);
    if (!m.find()) {
        return input;
    }
    StringBuilder outputBuilder = new StringBuilder(input.subSequence(0, m.start()));
    int lastEnd = m.end();
    outputBuilder.append(getChar(m));

    while (m.find()) {
        outputBuilder.append(input.subSequence(lastEnd, m.start()))
                .append(getChar(m));
        lastEnd = m.end();
    }

    if (lastEnd != input.length()) {
        outputBuilder.append(input.subSequence(lastEnd, input.length()));
    }

    return outputBuilder.toString();
}

private static String getChar(Matcher m) {
    return new String(new byte[] {
        Byte.parseByte(m.group(1), 16),
        Byte.parseByte(m.group(2), 16),
    });
}

示例:

replaceCharEscapes("\\u0043:\\\\u0050\\u0072\\u006f\\u0067\\u0072\\u0061\\u006ds")

返回C:\Programs