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?
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'.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With