[solved] Reading commands without waiting

I’m trying to read commands the user enters into cmd, but the only way I’ve been able to implement it is like this:

Scanner scanner = new Scanner(System.in);
String command = "";
while(true){
    command = scanner.nextLine();
    doCommand(command);
}

This results in the application waiting for the next command from the user, it can’t do anything else. Is there another way I can do this?

The simplest way would be by using another thread which would report that something was entered in the console.

Also, it would really depend on what you are trying to achieve. Are you writing a console application or a game of some sorts?

Its a Kroynet server, I’d like to give it some commands like stop, kick andvarious admin tools.

You will either want to develop a GUI for the server that allows you to type in commands or run your input on a separate thread.

The thread way is quicker but might not be as nice.

Thanks for that, I moved the command listening to another thread.

I would recommend using a GUI.

The reason for this is because when you add a listener for the keypress [enter] or when you press send, its technically on a new thread anyhow so you don’t need to mess around with anything, but make it practical, this gui took me 4 days to make to the spec i needed xD (Hate positioning jframe stuff)

Yeah I’d like to use a GUI but I want to get things working first. The server can run fine with cmd so I’ll stick with it for now.

Actually there is no need to use a different thread. The InputStream has an available() method which estimates how many bytes are available to read at that instant without blocking (according to the javadoc). In the case of System.in, it will be the number of characters available to read in at the command line (not an estimate).

An easier way though would be to wrap it up in a BufferedReader so you can read a whole line at a time with one method call in which case you are using the ready() method. Similarly, it returns true if the next read() command is guaranteed not to block.


//In Initialization
BufferedReader sysInReader = new BufferedReader(new InputStreamReader(System.in));

...

//In loop
if(sysInReader.ready()) {
    doWhateverWith(sysInReader.readLine());
}