因此,我尝试从键盘 ( 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()
可能会有所帮助,但是null
在诸如 NetBeans 之类的 IDE 环境下运行时会返回。还有什么可以尝试的?我需要我的程序做的就是从键盘接受非 ASCII 文本并将这个输入存储为一个String
对象。