Is there an easy way to read a single char from the console as the user is typing it in Java? Is it possible? I've tried with these methods but they all wait for the user to press enter key:
char tmp = (char) System.in.read();
char tmp = (char) new InputStreamReader(System.in).read ();
char tmp = (char) System.console().reader().read(); // Java 6
I'm starting to think that System.in is not aware of the user input until enter is pressed.
You need to knock your console into raw mode. There is no built-in platform-independent way of getting there. jCurses might be interesting, though.
On a unix system, this might work:
For example, if you want to take into account the time between keystrokes, here's sample code to get there.
What you want to do is put the console into "raw" mode (line editing bypassed and no enter key required) as opposed to "cooked" mode (line editing with enter key required.) On UNIX systems, the 'stty' command can change modes.
Now, with respect to Java... see Non blocking console input in Python and Java. Excerpt:
One of the suggestions is to use JNI. Again, that's not very portable. Another suggestion at the end of the thread, and in common with the post above, is to look at using jCurses.
I have written a Java class RawConsoleInput that uses JNA to call operating system functions of Windows and Unix/Linux.
_kbhit()
and_getwch()
from msvcrt.dll.tcsetattr()
to switch the console to non-canonical mode,System.in.available()
to check whether data is available andSystem.in.read()
to read bytes from the console. ACharsetDecoder
is used to convert bytes to characters.It supports non-blocking input and mixing raw mode and normal line mode input.
There is no portable way to read raw characters from a Java console.
Some platform-dependent workarounds have been presented above. But to be really portable, you'd have to abandon console mode and use a windowing mode, e.g. AWT or Swing.
Use jline3:
Example: