Java: read key from console without press enter ke

2019-02-14 05:19发布

问题:

I want to interrupt the program when user press especific key. I try the code bellow, but its only work with enter key.

java.io.InputStreamReader reader = new java.io.InputStreamReader(System.in); 
boolean b = false;
while(!b) 
{ 
    try{
        if ( reader.ready()) 
        { 
            // read a character and process it 
            System.out.println("key pressed");
            b = true;
        } 
    }
    catch (java.io.IOException ioex)
    {
        System.out.println("IO Exception");
    }

    // edit, lets not hog any cpu time 
    try 
    { 
        Thread.sleep(50); 
        System.out.println("nop yet");
    } 
    catch (InterruptedException ex) 
    { 
        // can't do much about it can we? Ignoring  
        System.out.println("Interrupted Exception");
    } 
}

Equivalent in C# (working):

    ConsoleKeyInfo k1 = new ConsoleKeyInfo('T', ConsoleKey.T, false, false, false);
    ConsoleKeyInfo k = Console.ReadKey(false);

    if (k== k1)
    {
        Environment.Exit(1);
    }

Edit 1:

I tried with threads and this listners, but not works too.

    public void keyTyped(KeyEvent e)
    public void keyPressed(KeyEvent e)
    public void keyReleased(KeyEvent e)