Java字符串和键盘的非ASCII输入

时间:2015-11-20 03:23:14

标签: java string non-ascii-characters keyboard-input

所以我试图从键盘(System.in)中获取非ASCII文本,例如中文字符,并将此文本放入String对象中。但是我这样做有些麻烦。我的第一次尝试使用了Scanner对象:

try(Scanner keyboard = new Scanner(System.in, "UTF-8"))
{
    System.out.println("Enter text to search for (case sensitive):");
    String searchKey = keyboard.nextLine();
    ...

如果用户通过键盘输入非ASCII文本,例如狂浪逆袭包,searchKey将填充垃圾。 searchKey的字面含义变为“?????” (没有引号,因此它填充了'?'字符)。做类似的事情:

byte[] strBytes = searchKey.getBytes("UTF-8");

表明strBytes中的所有元素都等于0x3f,这是'?'的ASCII代码。我也试过使用读者流:

try(BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in, "UTF-8")))
{
    System.out.println("Enter text to search for (case sensitive):");
    String searchKey = keyboard.readLine();
    ...

但是有了这个,我得到了与使用Scanner时完全相同的结果。字节流也不会改变任何东西:

try(DataInputStream keyboard = new DataInputStream(System.in))
{
    System.out.println("Enter text to search for (case sensitive):");
    String searchKey = keyboard.readLine();
    ...

我读到System.console()可能会有所帮助,但在NetBeans等IDE环境下运行时会返回null。还有什么可以尝试的?我需要我的程序才能接受键盘上的非ASCII文本并将此输入存储为String对象。

0 个答案:

没有答案
相关问题