如何让System.in输入流读取utf-8字符? [英] How can I make System.in Input Stream read utf-8 characters?
本文介绍了如何让System.in输入流读取utf-8字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的代码:
public class MyTestClass {
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(System.in);
String s = scanner.nextLine();
InputStream inputStream = System.in;
int read = inputStream.read();
System.out.println(read);
System.out.println((char)read);
System.out.println(s);
}
}
我输入字母 ğ
运行程序时两次。控制台输出将是:
And I input the letter ğ
twice when I run the program. The console output will be:
ğ
ğ
196
Ä
ğ
如何才能看到正确的字母,而不是Ä
?扫描仪似乎做对了。
How can I see the correct letter instead of Ä
? Scanner seems to do the right thing.
实际上,为什么这种方法不起作用?这里有什么问题?
And actually, why does not this approach work? What is wrong in here?
推荐答案
将 InputStream
包装在 InputStreamReader中
。
int read = new InputStreamReader(System.in).read();
System.out.println((char) read); // prints 'ğ'
如有必要,您可以传递特定的 Charset
到读者的构造函数,但默认情况下,它只使用默认的字符集,这可能是正确的。
If necessary, you can pass a specific Charset
to the reader's constructor, but by default, it will just use the default charset, which is probably correct.
这篇关于如何让System.in输入流读取utf-8字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文