【发布时间】:2014-09-02 07:18:58
【问题描述】:
我正在尝试将 URL 编码的 ASCII 字节数组转换为 Java 中的 UTF-8。
输入 ASCII 字符串 Fa%C3%A7ade 应转换为输出 UTF-8 字符串 Façade。
【问题讨论】:
-
icza 是对的,您的输入不是 ASCII 并且不需要将 ASCII 转换为 UTF-8,因为它是的子集。
我正在尝试将 URL 编码的 ASCII 字节数组转换为 Java 中的 UTF-8。
输入 ASCII 字符串 Fa%C3%A7ade 应转换为输出 UTF-8 字符串 Façade。
【问题讨论】:
您的输入字符串不是 ASCII 而是 URL 编码的字符串。
你可以这样解码:
String s = "Fa%C3%A7ade";
System.out.println(URLDecoder.decode(s, "UTF-8"));
Java 中的String 表示为字符数组 (char[]),它没有以任何编码方式进行编码。当String 转换为字节数组或字节数组转换为String 时,编码开始发挥作用。
因此,如果您有一个使用 UTF-8 编码的 String 字节数组,您可以将其转换为 String,如下所示:
byte[] arr = {104, 101, 108, 108, 111};
String s = new String(arr, StandardCharsets.UTF_8);
System.out.println(s); // Prints "hello"
// Or your input string would be:
arr = {70, 97, -61, -89, 97, 100, 101};
s = new String(arr, StandardCharsets.UTF_8);
System.out.println(s); // Prints "Façade"
【讨论】:
怎么样
new String (bytes, "UTF-8");
【讨论】:
使用 Apache commons-codec
byte[] bytes = StringUtils.getBytesUtf8(asciiString);
String utfString = new String(bytes);
【讨论】: