Read Japanese Character using Scanner

牧云@^-^@ 提交于 2020-01-13 19:26:34

问题


Possible duplicate: How can I read Chinese characters correctly using Scanner in Java?

My input file name may have japanese characters and I am trying to read the file name using Scanner.

Scanner sc = new Scanner(System.in,"utf-8");
System.out.println("Encoding is :" + Charset.defaultCharset());

System.out.println("Enter the path:");
inputFilePath = sc.nextLine();

and if my input is for eg - 漢字

When I print the file name my output is

Encoding is :UTF-8
Input File Path:漢字

I also tried,

byte[] jis = sc.nextLine().getBytes("Shift_JIS");
System.out.println(new String(jis));

and My output was

Input File Path:??��??�\

How can I rectify this?


回答1:


Eclipse is reading from the Console which is set by default as UTF-8. To read the data you need to change the console encoding to Japanese supported encoding.

In the Run Configuration, change the encoding to Japanese supported encoding and try again.




回答2:


Your code is correct, only issue is you are reading utf-8 and then converting it to Shift_JIS which prints junk characters.

Have you tried using this.

Scanner sc = new Scanner(System.in,"utf-8");
System.out.println("Encoding is :" + Charset.defaultCharset());

System.out.println("Enter the path:");
String inputFilePath = sc.nextLine();
System.out.println("Input path:" + new String(inputFilePath.getBytes("utf-8")));

Hope this helps !!




回答3:


This Answer for Chinese

Every String is already (conceptually) a sequence of characters, including Chinese characters.. Encoding only comes into it when you need to convert it into a bytes, which you don't need to for your assignment. Just use the String's hashcode. In fact, when you create a HashMap, that's exactly what will happen behind the scene



来源:https://stackoverflow.com/questions/14974326/read-japanese-character-using-scanner

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!