gpt4 book ai didi

java - 无法通过 System.in 读取日语字符

转载 作者:行者123 更新时间:2023-12-02 09:36:45 25 4
gpt4 key购买 nike

代码:

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"));

输入:

Enter Name : たなかです

输出:

�F�Q���N�@

鐃�鐃�鐃緒申鐃�鐃�

�ソスF�ソスQ�ソス�ソス�ソスN�ソス@

���F���Q���������N���@

�F�Q���N�@

它们都不是可读的日语。我还尝试了 InputStreamReaderDataInputStream 以及 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 对象>.

关于java - 无法通过 System.in 读取日语字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36261043/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com