Tony R Tony R - 5 years ago 140
Java Question

How to asynchronously read stdin?

Is there an elegant way to fire an event when characters are available from

System.in
? I'd like to avoid polling
InputStream.available()
.

Answer Source

You would have to create a separate thread that blocks in read until something is available.

If you don't want to actually eat up the input, you would have to wrap it with an internal buffer, read into the buffer, shout, and when asked for the input, give back data from the buffer.

You could solve it like this:

InputStream stdin = System.in;

// Create a wrapper (with it's own dedicated read-thread)
MyListenableInputStream listenableInputStream =
        new MyListenableInputStream(stdin);

// Update System.in with something more useful.
System.setIn(listenableInputStream);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download