我在Java中有一段代码打印出一个字符串:
String original = new String("A" + "\u00ea" + "\u00f1" + "\u00fc" + "C");
byte[] utf8Bytes = original.getBytes("UTF8");
String roundTrip = new String(utf8Bytes, "UTF8");
System.out.println("roundTrip = " + roundTrip); // Output is [roundTrip = AêñüC]
当我在Scala中运行这段Java代码时,我会回到AΩ±ⁿC
如果我以十六进制打印字符串,Scala和Java的输出相互匹配。
try {
String original = new String("A" + "\u00ea" + "\u00f1" + "\u00fc" + "C");
byte[] utf8Bytes = original.getBytes("UTF8");
byte[] defaultBytes = original.getBytes();
String roundTrip = new String(utf8Bytes, "UTF8");
printBytes(utf8Bytes, "utf8Bytes");
System.out.println();
printBytes(defaultBytes, "defaultBytes");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
这是输出:
utf8Bytes[0] = 0x41
utf8Bytes[1] = 0xc3
utf8Bytes[2] = 0xaa
utf8Bytes[3] = 0xc3
utf8Bytes[4] = 0xb1
utf8Bytes[5] = 0xc3
utf8Bytes[6] = 0xbc
utf8Bytes[7] = 0x43
defaultBytes[0] = 0x41
defaultBytes[1] = 0xc3
defaultBytes[2] = 0xaa
defaultBytes[3] = 0xc3
defaultBytes[4] = 0xb1
defaultBytes[5] = 0xc3
defaultBytes[6] = 0xbc
defaultBytes[7] = 0x43
参考:https://docs.oracle.com/javase/tutorial/i18n/text/string.html
编辑: 我使用Scala调用Java代码。
Scala的推出方式与Java有何不同?我怎么能修复Scala以便它能给我与Java的相同的输出?