Re: Reading keystrokes using Java under Linux terminals?
Ivan_G_S wrote:
hello, community!
i am trying to read single characters and keystrokes with a java
console application using linux terminals (konsole, xterm).
int inputChar = 0;
while ((inputChar = System.in.read()) != -1) {
char input = (char) inputChar;
System.out.print(" <" + input + "> ");
System.out.flush();
}
but instead of getting one keystroke after another, i get them all at
once after pressing return.
Because that's how consoles work, most of the time. The console has a
line buffer, and <Enter> commits the buffer. If you don't want this,
you'll want to use something called curses. Google gets
<http://sourceforge.net/projects/javacurses/>, but I have no experience
with that whatsoever. It appears to be something designed more for the
GUI side and styled similar to the AWT, though; it should still allow
you to get characters correctly, though.
^[[A^[[B^[[D^[[C^[
after pressing return, only [ appears.
Is that what's being printed by the application or not? Use integral
output (i.e. (int) input or just inputChar if you prefer) to see what's
really going on.
If it's not what's being printed, welcome to the wonderful world of ANSI
terminal escape codes. You have moved the cursor first up a row, than
down a row, left a column, and finally right a column. See
<http://en.wikipedia.org/wiki/ANSI_escape_code> for more information.
--
Beware of bugs in the above code; I have only proved it correct, not
tried it. -- Donald E. Knuth