无法通过System.in读取日文字符

时间:2016-03-28 11:06:02

标签: java character-encoding 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"));

输入:

  

输入姓名:たなかです

输出:

  

FQN @

     

铙铙铙绪申铙铙

     

ソス˚FソスQソスソスソスÑソス@

     

FQN @

     

�F�Q���N�@

它们都不是日语可读的。 我还尝试了InputStreamReaderDataInputStreamByte[]

2 个答案:

答案 0 :(得分:0)

如何正确打印字符串以使用代码进行控制台

您代码中的

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")。您可以使用String将其反转为System.out.println(new String(name.getBytes("UTF-16"), "UTF-16"));对象。

答案 1 :(得分:-1)

您的以下代码段中存在轻微问题,您对不同的字符集使用相同的编码,

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