How to asynchronously read stdin?

前端 未结 5 476
遥遥无期
遥遥无期 2021-01-14 05:23

Is there an elegant way to fire an event when characters are available from System.in? I\'d like to avoid polling InputStream.available().

5条回答
  •  执笔经年
    2021-01-14 06:12

    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);
    

提交回复
热议问题