Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wait for a key press in Clojure

Tags:

clojure

kbhit

I'd like to break out of a loop when the user presses a key.

In C I'd use kbhit(). Is there a Clojure (or Java) equivalent?

like image 884
justinhj Avatar asked Dec 18 '10 18:12

justinhj


1 Answers

You're looking for nonblocking handling of a key press in a (Linux?) console in Java. An earlier question suggested two Java libraries that might enable this. If it doesn't need to be portable, there is a solution here.

Basically,

public class Foo {
  public static void main(String[] args) throws Exception {
    while(System.in.available() == 0) {
       System.out.println("foo");
       Thread.sleep(1000);
    }
  }
}

works, but (on Linux) only after pressing 'return', because the console inputstream is buffered and that is decided by the OS. This means that you can't overcome that by using Channels or any other NIO class. To make sure the console flushes each and every character, you need to modify the terminal settings. I once wrote a C program that does that (modify the ICANON flag of the termios struct of the current terminal), but I don't know how to do that from Java (but see the second link).

In general, you can find some more in this issue by searching for 'java nonblocking input'.

like image 80
Confusion Avatar answered Oct 04 '22 17:10

Confusion