Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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().

like image 927
Tony R Avatar asked Nov 29 '25 17:11

Tony R


2 Answers

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);
like image 130
aioobe Avatar answered Dec 02 '25 05:12

aioobe


Sure...start a thread that blocks on the input and then calls your event method when it gets something.

like image 38
JOTN Avatar answered Dec 02 '25 06:12

JOTN