为什么我们不能一次从System.in读取一个字符? [英] Why can't we read one character at a time from System.in?
问题描述
下面的程序打印标准写入的每个字符,但只有在写完新行之后(至少在我的系统上!)。
The program below prints each character written on standard in, but only after a new-line has been written (at least on my system!).
public class Test {
public static void main(String[] args) throws java.io.IOException {
int c;
while ((c = System.in.read()) != -1)
System.out.print((char) c);
}
}
这可以防止人们写按任意键之类的内容继续并强迫类似按输入继续。
This prevents people from writing stuff like "Press any key to continue" and forces something like "Press enter to continue."
- 这是什么原因?
- 它是Java的限制吗?
- 这种行为是否与系统有关(我在Ubuntu上)?它在Mac上如何运作? Windows?
- 它是否依赖于我运行应用程序的特定终端? (对我而言,它在Eclipse和gnome-terminal中的行为相似)
- 是否有解决方法?
- What is the underlying reason for this?
- Is it a limitation of Java?
- Is this behavior system-dependent (I'm on Ubuntu)? How does it work on Mac? Windows?
- Is it dependent on the specific terminal I run the application in? (For me it behaves like this in Eclipse and in gnome-terminal)
- Is there a workaround?
推荐答案
这是什么原因?
What is the underlying reason for this?
默认情况下,大多数终端都是行缓冲的,Java在换行之前不会接收输入。
Most terminals is line buffered by default, Java does not receive input until a newline.
这是Java的限制吗?
Is it a limitation of Java?
一些古老的终端可能只有线路缓冲输入;虽然应该可以在大多数现代终端中禁用缓冲。
Some ancient terminals might only have line-buffered input; though it should be possible to disable buffering in most modern terminal.
这种行为是否与系统有关(我在Ubuntu上)?它在Mac上如何运作? Windows?
Is this behavior system-dependent (I'm on Ubuntu)? How does it work on Mac? Windows?
是。
是它依赖于我运行应用程序的特定终端? (对我来说,它在Eclipse和gnome-terminal中表现得像这样)
Is it dependent on the specific terminal I run the application in? (For me it behaves like this in Eclipse and in gnome-terminal)
是。
是否有解决方法?
Is there a workaround?
有特定于平台的黑客攻击。 Linux和类Unix平台中的诅咒
和Windows中的getch()。我不知道任何跨平台的方式。
There are platform specific hacks. curse
in Linux and Unix-like platforms, and getch() in Windows. I'm not aware of any cross-platform way.
相关:为什么按任意键继续是个坏主意:
related: Why "Press any key to continue" is bad idea:
这篇关于为什么我们不能一次从System.in读取一个字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!