我的程序正在从浏览器应用程序接收一个被解释为 UTF-8 的整数数组(代码中的示例)。我可以将生成的字符串(下面代码中显示的“theString”)回显到浏览器,一切都很好。但在Java程序中就不行了。输入字符串是“Hällo”。但它从 Java 程序中打印出来为“Hõllo”。
import java.io.*;
import java.nio.charset.*;
public class TestCode {
public static void main (String[] args) throws IOException {
// H : 72
// ä : 195 164
// l : 108
// o : 111
// the following is the input sent from browser representing String = "Hällo"
int[] utf8Array = {72, 195, 164, 108, 108, 111};
String notYet = new String(utf8Array, 0, utf8Array.length);
String theString = new String(notYet.getBytes(), Charset.forName("UTF-8"));
System.out.println(theString);
}
}
最佳答案
这就能解决问题:
int[] utf8Array = {72, 195, 164, 108, 108, 111};
byte[] bytes = new byte[utf8Array.length];
for (int i = 0; i < utf8Array.length; ++i) {
bytes[i] = (byte) utf8Array[i];
}
String theString = new String(bytes, Charset.forName("UTF-8"));
直接传递 int[]
的问题是 String
类将每个 int
解释为单独的字符,而在转换为 byte[]
String
将输入视为原始字节,并理解 195, 164
实际上是由两个字节而不是两个字符组成的单个字符。
更新:不幸的是,回答您的评论,Java 就是那么冗长。与 Scala 比较:
val ints = Array(72, 195, 164, 108, 108, 111)
println(new String(ints map (_.toByte), "UTF-8"))
再次强调,int
和 byte
之间的区别不仅仅是编译器的挑剔,它们在 UTF-8 编码方面确实意味着不同的东西。
关于Java:在 Java 程序中解释 UTF-8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7273814/