views:

4481

answers:

3

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 both 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.

A: 

Java 6 Console would help i think.

emeraldjava
I've tried char tmp = (char) System.console().reader().read(); too and it blocks the input. Forgot to mention it sorry
victor hugo
+4  A: 

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:

If your program must be console based, you have to switch your terminal out of line mode into character mode, and remember to restore it before your program quits. There is no portable way to do this across operating systems.

There's also an interesting discussion thread here. 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.

Chris W. Rea
JCurses is not very portable either.... From the JCurses README: "JCurses consists of two parts: the plattform independent part,and plattform dependent part, that consists of a native shared library making primitive input and output operations available to the first part."
Ryan Fernandes
I was afraid of this...
victor hugo
A: 

(char) System.console().reader().read(); It is OK but there is some problem as follow Exception in thread "main" java.lang.NullPointerException at Characters.main(Characters.java:

salem
That's just because there's no console. Likely you're running this in an IDE instead of command prompt. In the future, please don't post questions/problems as an answer, but just as a new question.
BalusC