[英]Fail to read Japanese Characters via System.in
代码:
Scanner sc = new Scanner(System.in);
System.out.println("Enter Name : ");
String name = sc.nextLine();
System.out.println(name);
String encoding = "UTF-8";
System.out.println(new String(name.getBytes(encoding), "euc-jp"));
System.out.println(new String(name.getBytes(encoding), "Shift_JIS"));
System.out.println(new String(name.getBytes(encoding), "ISO-2022-JP"));
System.out.println(new String(name.getBytes(encoding), "ISO8859-1"));
输入:
输入名称:たなかです
输出:
F Q N@
铙 铙 铙绪申铙 铙
...
F Q N @
�F�Q���N�@
它们都不是可读的日语。 我也试过InputStreamReader
和DataInputStream
与Byte[]
。
代码中的name.getBytes(encoding)
将使用 UTF-8 编码获取String name
的原始字节表示。 所以当你在控制台输入“たなかです”时,你会得到字节数组{0xE3, 0x81, 0x9F, 0xE3, 0x81, 0xAA, 0xE3, 0x81, 0x8B, 0xE3, 0x81, 0xA7, 0xE3, 0x81, 0x99}
它是基于 UTF-8 的表示,因此您可以在构造函数String(byte[] bytes, String charsetName)
的第二个参数中指定的唯一编码是UTF-8
。
System.out.println(new String(name.getBytes(encoding), "UTF-8"));
它将字节数组{0xE3, 0x81, 0x9F, ... }
转换为String
对象,并正确打印到控制台。
String
对象使用 UTF-16 作为内部文本表示(有关详细信息,请参阅https://docs.oracle.com/javase/8/docs/technotes/guides/intl/overview.html )。
因此,当您想要获取与内部文本表示相同的字节数组时,您必须使用name.getBytes("UTF-16")
。 您可以使用System.out.println(new String(name.getBytes("UTF-16"), "UTF-16"));
将其反转为String
对象System.out.println(new String(name.getBytes("UTF-16"), "UTF-16"));
.
您的以下代码片段中存在小问题,您对不同的字符集使用相同的编码,
String encoding = System.getProperty("file.encoding");
System.out.println(new String(name.getBytes(encoding), "UTF-8"));
假设您想使用不同的字符集打印日语字符,请使用此
System.out.println(new String(name.getBytes("euc-jp"), "euc-jp"));
System.out.println(new String(name.getBytes("Shift_JIS"), "Shift_JIS"));
System.out.println(new String(name.getBytes("ISO-2022-JP"), "ISO-2022-JP"));
System.out.println(new String(name.getBytes("ISO8859-1"), "ISO8859-1"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.