This is more complicated than it seems, mainly due to the way Java works on different platforms. The main solution for reading from the keyboard is to use stdin, for example:
InputStream in = System.in; int next = 0; do { next = in.read(); System.out.println("Got " + next); } while (next != -1);
Now there are two problems:
- On unix platforms, this will not print the next character as soon as it has been pressed, but only after the return button has been pressed, since the operating system buffers the default input
There is no ascii code for the arrow keys, instead there are so-called escape sequences that depend on the terminal emulator used, so on my Mac, if I run the above code and press Arrow-Up and then key returns, I get the following output:
Got 27
There is no good platform-independent, independent way, if you only target unix platforms, javacurses can help.
source share